Java 如何将HashMap添加到HashMap的HashMap中而不被覆盖

Java 如何将HashMap添加到HashMap的HashMap中而不被覆盖,java,hashmap,Java,Hashmap,我有两个哈希图 Map<Integer, HashMap<String,Integer>> outer = new HashMap<Integer,HashMap<String,Integer>>(); HashMap<String, Integer> inner =new HashMap<String, Integer>(); 在每次迭代之后,我使用一个全局变量(publicstatichashmap tem

我有两个哈希图

 Map<Integer, HashMap<String,Integer>> outer = new HashMap<Integer,HashMap<String,Integer>>();
     HashMap<String, Integer> inner =new HashMap<String, Integer>();
在每次迭代之后,我使用一个全局变量(publicstatichashmap tempMap=null;)将内部添加到外部

当我打印outer时,我发现每个元素都包含inner的最终版本。 如何防止此数据被覆盖。我采纳了关于这个主题的其他几个问题的建议,将inner传递到一个全局变量中,但它似乎不起作用


谢谢

一般的java概念是通过引用调用的。
如果不想覆盖信息,则必须每次复制内部映射或创建一个新映射。

您可以在每次迭代时克隆内部映射。但是它会消耗更多的内存

tempMap = inner;
outer.put(count, tempMap.clone());
count++;

这是因为tempMap是通过引用而不是作为单独的对象保存在HashMap中的。

您意识到您只是在HashMap中存储引用,对吗?如果你想让每一个都不同,你需要显式地复制。不要让
tempMap=newhashmap
可能是正确的解决方案,但是如果不显示一个值,就很难知道你在做什么以及为什么它不起作用
        tempMap = inner;
        outer.put(count, tempMap);
        count++;
tempMap = inner;
outer.put(count, tempMap.clone());
count++;