下面展示 putAll()方法。
import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * @author DingZhenYun * @create 2020-09-03 21:19 */ public class Test1 { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(100); list.add(200); HashMap<String,Object> map = new HashMap<String,Object>(); //放基本类型数据 map.put("basic", 100); //放对象 map.put("list", list); HashMap<String,Object> mapNew = new HashMap<String,Object>(); mapNew.putAll(map); System.out.println("----数据展示-----"); System.out.println(map); System.out.println(mapNew); System.out.println("----更改基本类型数据-----"); map.put("basic", 200); System.out.println(map); System.out.println(mapNew); System.out.println("----更改引用类型数据-----"); list.add(300); System.out.println(map); System.out.println(mapNew); System.out.println("----使用序列化进行深拷贝-----"); mapNew = Test1.myClone(map); list.add(400); System.out.println(map); System.out.println(mapNew); } @SuppressWarnings("unchecked") public static <T extends Serializable> T myClone(T obj){ T clonedObj = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); clonedObj = (T) ois.readObject(); ois.close(); }catch (Exception e){ e.printStackTrace(); } return clonedObj; } }结果代码:
----数据展示----- {basic=100, list=[100, 200]} {basic=100, list=[100, 200]} ----更改基本类型数据----- {basic=200, list=[100, 200]} {basic=100, list=[100, 200]} ----更改引用类型数据----- {basic=200, list=[100, 200, 300]} {basic=100, list=[100, 200, 300]} ----使用序列化进行深拷贝----- {basic=200, list=[100, 200, 300, 400]} {basic=200, list=[100, 200, 300]}