import java.util.*;
public class ArrayListShadowCloneTest {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
//添加两个元素
Student stJack=new Student("Jack", 13);
Student stTom=new Student("Tom", 15);
list.add(stJack);
list.add(stTom);
//克隆
ArrayList<Student> listCopy=(ArrayList<Student>) list.clone();
stJack.setName("balbaol");
//改变stJack的name,导致list和listCopy都改变,验证了浅拷贝
System.out.println(list.get(0).toString());
System.out.println(listCopy.get(0).toString());
}
static class Student{
private String name;
private int age;
public void setName(String name){
this.name = name;
}
Student(String name, int age){
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}
一段能验证ArrayList的clone()方法是浅拷贝的代码
最新推荐文章于 2024-02-20 00:06:06 发布