1 回答

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
您都指向相同innerMap的對(duì)象outerMap,
outerMap.put("1001",new HashMap<String, Integer>());//create separate maps
outerMap.put("1002",new HashMap<String, Integer>());
outerMap.put("1003",new HashMap<String, Integer>());
HashMap<String, Integer> innerMap =outerMap.get("1001");//get the map you want to put value
innerMap.put("1", 1);//assign the value
更新:
如果要保留Map已創(chuàng)建的副本,Map可以使用putAll方法從中復(fù)制并創(chuàng)建新副本,
outerMap.put("1001",copyMap(innerMap));
outerMap.put("1002",copyMap(innerMap));
outerMap.put("1003",copyMap(innerMap));
copyMap 方法看起來像,
private static HashMap<String, Integer> copyMap(HashMap<String, Integer> innerMap){
HashMap<String, Integer> copiedInnerMap = new HashMap<String, Integer>();
copiedInnerMap.putAll(innerMap);
return copiedInnerMap;
}
添加回答
舉報(bào)