有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

排序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");
                    }
                }

我的代码可以写所有外键都有,并且第一个元素是整数1但看不到列表等等
如何与内部hashmap和外部hashmap建立连接


共 (2) 个答案

  1. # 1 楼答案

    通过^{}将整个对象存储为文件怎么样?比如:

    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接口才能使用此对象序列化

  2. # 2 楼答案

    序列化inner变量,它将负责序列化其内部保存的所有引用

    顺便提一下,为什么需要这样一个嵌套的数据结构?闻起来像是设计问题