定义
简单说就是复制已经存在的实例,创建新的实例。
注意
分深拷贝,和浅拷贝。 使用时候,避免错误使用深拷贝吧。
通过实现Cloneable接口,重写Object的clone方法实现
拷贝对象可以调用 super.clone(),简单也可以直接new一个在赋值
java实现 调用 super.clone()实现
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
{
@Override
public Object clone() {
HashMap<K,V> result;
try {
result = (HashMap<K,V>)super.clone();
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
result.reinitialize();
result.putMapEntries(this, false);
return result;
}
}
java实现 调用 new 实现
public class Intent implements Parcelable, Cloneable {
@Override
public Object clone() {
return new Intent(this);
}
}
kotlin实现
kotlin 语言支持了这个特性,数据类直接内部实现,提供了copy函数