一.创建复制Map对象方法
/**
* 复制map对象
*
* @param paramsMap 被拷贝对象
* @param resultMap 拷贝后的对象
* @explain 将paramsMap中的键值对全部拷贝到resultMap中;
* paramsMap中的内容不会影响到resultMap(深拷贝)
*/
public static void mapCopy(Map resultMap, Map paramsMap) {
if (resultMap == null) resultMap = new HashMap();
if (paramsMap == null) return;
Iterator it = paramsMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
resultMap.put(key, paramsMap.get(key) != null ? paramsMap.get(key) : "");
}
}
public static void main(String[] args) {
Map<String, String> map1 = new HashMap<String, String>(1);
map1.put("name", "Marydon");
Map<String, Object> map2 = new HashMap<String, Object>(1);
map2.put("age", 20);
// 测试一:是否实现拷贝
mapCopy(map1, map2);
System.out.println(map1);// {age=20, name=Marydon}
System.out.println(map2);// {age=20}
// 测试二:拷贝后的map对象是否受原map对象的影响
map2.clear();
System.out.println(map1);// {age=20, name=Marydon}
System.out.println(map2);// {}
System.out.println("================================");
HashMap<String, Object> hm = new HashMap();
HashMap<String, Object> hmCopy = new HashMap();
hm.put("123", 123);
System.out.println(hm.get("123")); //123
hmCopy = hm;
hmCopy.remove("123");
System.out.println(hm.get("123"));//null
}