在Java中,深拷贝(Deep Copy)与浅拷贝(Shallow Copy)的主要区别在于:深拷贝会创建一个新对象,并递归地复制原对象中的所有属性,包括嵌套的对象;而浅拷贝仅复制对象本身及其基本类型属性,对于引用类型属性,浅拷贝只是复制了引用,而不是对象本身。 针对ArrayList的深拷贝,以下是几种常见的方法及代码示例: 1. 使用序列...
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...
下面是具体的实现代码: importjava.io.*;publicclassDeepCopyExample{publicstatic<T>ArrayList<T>deepCopyArrayList(ArrayList<T>original){ArrayList<T>copy=newArrayList<>();try{// 将原始ArrayList对象写入字节流ByteArrayOutputStreambaos=newByteArrayOutputStream();ObjectOutputStreamoos=newObjectOutputStream(baos)...
intage){this.name=name;this.age=age;}// 复制方法publicPersonclone(){try{return(Person)super.clone();}catch(CloneNotSupportedExceptione){thrownewRuntimeException(e);}}@OverridepublicStringtoString(){return"Person{name='"+name+'\''+", age="+age+'}';}}publicclassDeepCopy...
1publicstatic<T> List<T> deepCopy(List<T> src)throwsIOException, ClassNotFoundException {2ByteArrayOutputStream byteOut =newByteArrayOutputStream();3ObjectOutputStream out =newObjectOutputStream(byteOut);4out.writeObject(src);56ByteArrayInputStream byteIn =newByteArrayInputStream(byteOut.toByteArra...
//使用构造函数创建深拷贝ArrayList<Integer> deepCopyList =newArrayList<>(originalList); 在Java中,ArrayList的深拷贝可以通过构造一个新的ArrayList实例并将原始列表中的元素添加到新列表中来实现。这样做可以确保新列表拥有原始列表中所有元素的独立副本,而不是引用。
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...
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); ...
importcn.hutool.core.bean.BeanUtil;importjava.util.ArrayList;publicclassDeepCopyExample{publicstaticvoidmain(String[]args){// 创建一个原始的ArrayList并添加学生对象ArrayList<Student>originalList=newArrayList<>();originalList.add(newStudent("Tom",18));originalList.add(newStudent("Jerry",20));// 打印...