Cloneable简单使用(一)
1.类型:和序列化接口一样为标识性接口
2.主要作用:进行对象属性的复制。
根据给定的源对象复制出一份新的对象,新的对象有完全一致的数据拷贝
3.前提条件:
被克隆对象所在的类必须要实现Cloneable接口
必须重写clone方法
4.实例代码:
(一定要继承Cloneable接口,否则则会报CloneNotSupportedException 异常信息)
自定义类拷贝
public class CloneTest implements Cloneable {
private String name;
private int age;
public static void main(String[] args) throws CloneNotSupportedException {
CloneTest source = new CloneTest();
source.setName("w");
source.setAge(11);
Object target = source.clone();
System.out.println(target);
//目标地址是否一样
System.out.println(target==source);
}
集合的克隆使用
ArrayList底层实现了cloneable接口
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
/**
* ArrayList 集合进行克隆
*/
public class ArrayListClone {
public static void main(String[] args) {
ArrayList<String> list=new ArrayList<>();
list.add("1");
list.add("23");
list.add("4");
Object clone = list.clone();
System.out.println(list);
System.out.println(clone);
System.out.println(list==clone);
}
}
控制台输出结果为:
[1, 23, 4]
[1, 23, 4]
false