在Java中,深拷贝(Deep Copy)与浅拷贝(Shallow Copy)的主要区别在于:深拷贝会创建一个新对象,并递归地复制原对象中的所有属性,包括嵌套的对象;而浅拷贝仅复制对象本身及其基本类型属性,对于引用类型属性,浅拷贝只是复制了引用,而不是对象本身。 针对ArrayList的深拷贝,以下是几种常见的方法及代码示例: 1. 使用序列...
单元测试用例: @TestpublicvoidtestDeepCopy(){ArrayList<CustomObject>originalList=newArrayList<>();originalList.add(newCustomObject("Test"));ArrayList<CustomObject>copiedList=CopyUtil.deepCopy(originalList);copiedList.get(0).setName("Changed");assertNotEquals(originalList.get(0).getName(),copiedList...
下面是具体的实现代码: importjava.io.*;publicclassDeepCopyExample{publicstatic<T>ArrayList<T>deepCopyArrayList(ArrayList<T>original){ArrayList<T>copy=newArrayList<>();try{// 将原始ArrayList对象写入字节流ByteArrayOutputStreambaos=newByteArrayOutputStream();ObjectOutputStreamoos=newObjectOutputStream(baos)...
ArrayList<GuideGroup> questionGuideGroupList = (ArrayList<GuideGroup>) deepCopy(guideGroupList); questionAnswerManInfo.setGuideGroupList(questionGuideGroupList); 通过递归方式实现深度拷贝 通过递归方式,使用add方法实现深度拷贝 public void copy(List src,List dest){ for (int i = 0 ;i < src.size() ...
//使用构造函数创建深拷贝ArrayList<Integer> deepCopyList =newArrayList<>(originalList); 在Java中,ArrayList的深拷贝可以通过构造一个新的ArrayList实例并将原始列表中的元素添加到新列表中来实现。这样做可以确保新列表拥有原始列表中所有元素的独立副本,而不是引用。
List<User> oldList = new ArrayList<>(Arrays.asList(new User("test",1))); List<User> newList = CloneUtils.deepClone(oldList); System.out.println(oldList.get(0));//com.study.copy.CloneUtils$User@330bedb4 System.out.println(newList.get(0));//com.study.copy.CloneUtils$User@4f3f5...
dest = test.deepcopy(src); } catch (IOException e) { // todo auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // todo auto-generated catch block e.printStackTrace(); } System.out.println(src == dest); ...
1 public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException { 2 ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); 3 ObjectOutputStream out = new ObjectOutputStream(byteOut); 4 out.writeObject(src); 5 6 ByteArrayInputStream byteIn = new ByteArr...
Copy ArrayList的四种方式 简介 ArrayList是我们经常会用到的集合类,有时候我们需要拷贝一个ArrayList,今天向大家介绍拷贝ArrayList常用的四种方式。 使用构造函数 ArrayList有个构造函数,可以传入一个集合: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 public ArrayList(Collection<? extends E> c) { elementData...
深度Copy的实现方法 实现ArrayList的深度复制有多种方法,下面我们介绍其中的两种常用方法。 方法一:使用序列化和反序列化 importjava.io.*;publicclassDeepCopyUtil{publicstatic<T>ArrayList<T>deepCopy(ArrayList<T>original){try{ByteArrayOutputStreambos=newByteArrayOutputStream();ObjectOutputStreamoos=newObjectOutp...