我是Java新手,我想要做的是将HashMap
( hm )的所有键和值交换为HashMap
( hm2 ),反之亦然。我没有为这个问题找到任何解决方案,有可能吗?
import java.util.*;
class HashMapSwap{
public static void main(String args[]){
HashMap<Integer, String> hm = new HashMap<Integer, String>();
HashMap<Integer, String> hm2 = new HashMap<Integer, String>();
hm.put(3, "Mobile");
hm.put(11, "Tab");
hm2.put(4, "PC");
hm2.put(1, "Laptop");
Map tmp = new HashMap(hm);
tmp.keySet().removeAll(hm2.keySet());
hm2.putAll(tmp);
for(Map.Entry en:hm2.entrySet()){
System.out.println(en.getKey() + " " + en.getValue());
}
}
}
O / P:
1台笔记本电脑
3手机
4 PC
11标签
答案 0 :(得分:3)
// store first map in (new) temporary map
HashMap<Integer, String> tempMap = new HashMap<Integer, String>(hm);
// clear first map and store pairs of hm2
hm.clear();
hm.putAll(hm2);
// clear second map and store pairs of tempMap
hm2.clear();
hm2.putAll(tempMap);
// EDIT (hint from Palcente)
// optional: null the tempMap afterwards
tempMap = null;
答案 1 :(得分:2)
tmp可用于交换引用,如下所示。
HashMap<Integer, String> hm = new HashMap<Integer, String>();
HashMap<Integer, String> hm2 = new HashMap<Integer, String>();
hm.put(3, "Mobile");
hm.put(11, "Tab");
hm2.put(4, "PC");
hm2.put(1, "Laptop");
HashMap tmp = new HashMap();
tmp = hm;
hm = hm2;
hm2 = tmp;
for(Map.Entry en:hm.entrySet()){
System.out.println(en.getKey() + " " + en.getValue());
}
for(Map.Entry en:hm2.entrySet()){
System.out.println(en.getKey() + " " + en.getValue());
}