2012-01-15 148 views
3

所以我能寫:
Java:如何將HashMap <String,HashMap <Integer,ArrayList <Integer> >>寫入文件?

HashMap<String, ArrayList<Integer>> ... 

,但是當涉及到一個結構類似

HashMap<String, HashMap<Integer, ArrayList<Integer>>> ... 

我失敗了......

Set<String> keys = outer.keySet(); 
List<String> list = sortList(keys); 
Iterator<String> it = list.iterator(); 
HashMap<Integer,ArrayList<Integer>> inner=new HashMap<Integer,ArrayList<Integer>>(); 
       while (it.hasNext()) { 
        String key = it.next(); 
        Set<Integer> ids= inner.keySet(); 
        List<Integer> positions=sortList(ids); 
        Iterator<Integer> itIn=positions.iterator(); 
        while(itIn.hasNext()){ 
         String id= it.next(); 
         output.write(key + "\t" + outer.get(key) + " " +inner.get(id) +"\n"); 
        } 
       } 

我的代碼可以寫所有外部的鍵和第一個Integer1的元素,但不能看到列表等等。
如何與內部hashmap和外部hashmap建立連接?

+0

你確定你真的想寫這段代碼嗎?看看'inner'變量,你現在正在實例化它,你想迭代它嗎?該集合是空的,所以它裏面不能有任何值。 – SHiRKiT 2012-01-15 14:56:28

+0

我不是這個意思,這是我最好的想法。是的,我不知道如何將外部值整合到內部 – anonym 2012-01-15 15:04:59

+0

然後停止考慮hashmaps,arraylists等,並開始思考作爲矩陣。你在那裏有什麼?一個非常特殊的地圖。您將Srings映射到Integer,然後再映射到Integer。所以,在3D矩陣中思考,我們有Matrix [String] [Integer] [Integer]。如果你能想出更好的解決方案,試試這種方法。但是這在方法中看起來像是一個錯誤。認爲是一個3D矩陣,你會得到它。我已經成功地創建了一個序列化3D矩陣的想法,但是在使用HashMap >>時,事情變得非常複雜。 – SHiRKiT 2012-01-15 15:16:17

回答

3

如何通過ObjectOutputStream將整個對象存儲爲文件?喜歡的東西:

public static void saveObject(HashMap<String, HashMap<Integer, ArrayList<Integer>>> obj, String filePath) 
{ 
    OutputStream os = null; 
    try 
    { 
     os = new ObjectOutputStream(new FileOutputStream(filePath)); 
     os.writeObject(obj); 
    } 
    catch(Exception ex){} 
    finally 
    { 
     os.close(); 
    } 
} 

然後,你可以加載它想:

public static HashMap<String, HashMap<Integer, ArrayList<Integer>>> loadObject(String filePath) 
{ 
    HashMap<String, HashMap<Integer, ArrayList<Integer>>> obj = null; 
    InputStream is = null; 
    try 
    { 
     is = new ObjectInputStream(new FileInputStream(filePath)); 
     obj = (HashMap<String, HashMap<Integer, ArrayList<Integer>>>) is.readObject(); 
    } 
    catch(Exception ex){} 
    finally 
    { 
     is.close(); 
    } 
    return obj; 
} 

請注意,您需要實現Serializable接口來使用這個對象序列化。

0

inner變量進行序列化,它將負責序列化其保存的所有引用。

另外,爲什麼你需要這樣一個嵌套的數據結構?它聞起來像是一個設計問題。

+0

我正在爲大數據集中的每個獨特單詞存儲,定位索引和文件ID。要做到這一點,我認爲這種方式會更好。 – anonym 2012-01-15 15:09:48

+0

但是當然你可以以某種方式簡化設計,你創建的是可維護性頭痛 – 2012-01-15 15:11:22

相關問題