我有以下2个案例:
案例 1:
HashMap<String, HashMap<String,String>> mainMap = new HashMap<String, HashMap<String,String>>();
HashMap <String, String> subMap = new HashMap<String,String>();
subMap.put("11", "12");
subMap.put("13", "124");
subMap.put("21", "122");
subMap.put("14", "152");
System.out.println("For One : "+subMap);
mainMap.put("one", subMap);
subMap.put("15", "152");
subMap.put("17", "152");
System.out.println("For Two : "+subMap);
mainMap.put("two", subMap);
System.out.println(mainMap);
我期待以下输出:
For One : {21=122, 13=124, 14=152, 11=12}
For Two : {21=122, 17=152, 15=152, 13=124, 14=152, 11=12}
{two={21=122, 17=152, 15=152, 13=124, 14=152, 11=12}, one={21=122, 13=124, 14=152, 11=12}}
但是,我得到的是这个输出:
For One : {21=122, 13=124, 14=152, 11=12}
For Two : {21=122, 17=152, 15=152, 13=124, 14=152, 11=12}
{two={21=122, 17=152, 15=152, 13=124, 14=152, 11=12}, one={21=122, 17=152, 15=152, 13=124, 14=152, 11=12}}
案例 2:
我还尝试了以下方法:
HashMap<String,String> map12 = new HashMap<String, String>();
map12.put("1","1234");
map12.put("2","1234");
System.out.println("map12 : "+map12);
map12.put("3","1234");
我得到了预期的正确输出:
map12 : {2=1234, 1=1234}
为什么case1
中的代码没有给出预期的结果,但case2
却工作得很好?
最佳答案
mainMap 中的值是对 HashMap 对象的引用。对该对象的任何引用(例如 subMap)都可以更改它。
关于java - HashMap 没有得到预期的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23661758/