Java 如何将一个静态hashmap复制到另一个静态hashmap
如何将静态一个(A)hashmap值复制到静态另一个(B)hashmap,但如果更改了B hashmap中的任何值,则不应在A hashmap中反映 范例Java 如何将一个静态hashmap复制到另一个静态hashmap,java,android,Java,Android,如何将静态一个(A)hashmap值复制到静态另一个(B)hashmap,但如果更改了B hashmap中的任何值,则不应在A hashmap中反映 范例 public static HashMap<String,String> firstHashMap = new HashMap<String,String>(); firstHashMap.put("1","A"); firstHashMap.put("2","B"); public static HashMap&l
public static HashMap<String,String> firstHashMap = new HashMap<String,String>();
firstHashMap.put("1","A");
firstHashMap.put("2","B");
public static HashMap<String,String> secondHashMap = new HashMap<String,String>(firstHashMap);
secondHashMap.put("3","c");
secondHashMap.put("4","d");
publicstatichashmap firstHashMap=newhashmap();
firstHashMap.put(“1”、“A”);
firstHashMap.put(“2”,“B”);
public static HashMap secondHashMap=新HashMap(firstHashMap);
第二个hashmap.put(“3”,“c”);
第二个hashmap.put(“4”,“d”);
问题:这样做时,
firstHashMap
也包含secondHashMap
值
我们如何才能做到这一点?我需要
firstHashMap
应该只包含firstHashMap
值,而secondHashMap
应该同时包含这两个值
我还试着制作
secondHashMap.clone()代码>为什么不使用putAll
public static HashMap<String, String> firstHashMap = new HashMap<String, String>();
static {
firstHashMap.put("1", "A");
firstHashMap.put("2", "B");
}
public static HashMap<String, String> secondHashMap = new HashMap<String, String>();
static {
secondHashMap.put("3", "c");
secondHashMap.put("4", "d");
secondHashMap.putAll(firstHashMap);
}
publicstatichashmap firstHashMap=newhashmap();
静止的{
firstHashMap.put(“1”、“A”);
firstHashMap.put(“2”,“B”);
}
public static HashMap secondHashMap=new HashMap();
静止的{
第二个hashmap.put(“3”,“c”);
第二个hashmap.put(“4”,“d”);
putAll(firstHashMap);
}
它将替换公共键的值(这里没有),但也会放置新的键值对。您是否尝试过putAll(secondMap)
?ypu是否希望对firstMap的更改在secondMap中立即可见?或者它是从一个映射到另一个映射的所有值的一次性添加”,而firstHashMap
包含secondHashMap
值也“no aftersecondHashMap=new HashMap(firstHashMap)
secondHashMap
将复制firstHashMap
的值。就是这样。如果以后要向firstHashMap
添加内容,则在secondHashMap
中看不到它,反之亦然,如果将内容放入secondHashMap
中,则在firstHashMap
中看不到它。