ArrayList的clone方法探索,arraylistclone
分享于 点击 5482 次 点评:279
ArrayList的clone方法探索,arraylistclone
ArrayList的clone方法实现的是ArrayList对象的不完全深度拷贝,这是由对内部数组的拷贝造成的。内部数组实现的是对数组本身的深度拷贝,但没有实现对数组内容的深度拷贝,因此是个不完全的深度拷贝。对数组的深度拷贝,可以自己写其实现代码, 也可非常方便的调用数组的clone()方法,不管什么类型的数组都有一个clone方法, 该方法完成数组本身的深度拷贝,但如果数组中的内容是引用类型的变量,那么内容的深度拷贝需要自己实现。如:
package bzq12_29;
import java.util.ArrayList;
public class CopyTest
{
public static void main(String[] args)
{
Dog [] dogs = new Dog[2];
Dog d1 = new Dog("狗1", 2);
Dog d2 = new Dog("狗2", 3);
dogs[0] = d1;
dogs[1] = d2;
Dog [] copyOfDogs = makeCopyOfDogArray(dogs);
dogs[0].setAge(200);
System.out.println(copyOfDogs[0].getAge());
}
public static Dog[] makeCopyOfDogArray(Dog[] origin)
{
Dog [] copy = new Dog[origin.length];
for (int index = 0; index < origin.length; index++)
copy[index] = origin[index].clone();
return copy;
}
}
class Dog implements Cloneable
{
private String name;
private int age;
public Dog(String name, int age)
{
this.name = name;
this.age = age;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return age;
}
public Dog clone()
{
try
{
Dog copy = (Dog)super.clone();
return copy;
} catch (CloneNotSupportedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
相关文章
- 暂无相关文章
用户点评