Java:如何编写HashMap <string,hashmap <integer,=“”arraylist <integer =“”>&gt;&gt;到文件?</string,>

时间:2012-01-15 14:50:01

标签: java sorting arraylist hashmap

所以我能写:

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建立连接?

2 个答案:

答案 0 :(得分: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接口才能使用此对象序列化。

答案 1 :(得分:0)

序列化inner变量,它将负责序列化它所包含的所有引用。

另外,为什么需要这样的嵌套数据结构?它闻起来像是一个设计问题。

相关问题