public Object clone() { try { @SuppressWarnings("unchecked") ArrayList<E> v = (ArrayList<E>) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } }
當你須要使用remove方法移除掉集合中的對象,而非要修改集合中的對象的時候,能夠選擇使用。數組
//添加兩個元素 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(); //移除且不修改 listCopy.remove(1); System.out.println(list); System.out.println(listCopy);
代碼解讀:app
remove以前的:ide
remove以後的:this
因此移除且不修改集合中的元素,只是在List內部的數組中移除了指向元素的地址,能夠放心的使用clone。spa
若是你想要修改克隆後的集合,那麼克隆前的也會被修改。那麼就須要使用深複製。經過實現對象類的clone方法。code
public class testClone { public static void main(String[] args) { ArrayList<Student> list=new ArrayList<Student>(); //添加兩個元素 Student stJack=new Student("Jack", 13); Student stTom=new Student("Tom", 15); list.add(stJack); list.add(stTom); //深克隆 ArrayList<Student> listCopy=new ArrayList<Student>(); for (Student student : list) { listCopy.add(student.clone()); } //移除且不修改 listCopy.get(0).setAge(20); System.out.println(list); System.out.println(listCopy); } } class Student{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Student(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } @Override protected Student clone(){ Student stuent = new Student(this.name,this.age); return stuent; } }