一.創建復制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 }