标签:col ide cat ring exce container tostring prot port
clone
方法是Object
类提供的一个用于对象拷贝的方法,且是protected
,使用时需要类实现java.lang.Cloneable
接口,否则将抛出CloneNotSupportedException
异常
// java.lang.Object
protected native Object clone() throws CloneNotSupportedException;
使用clone
通常遵循的约定:
x.clone() != x
返回turex.clone().getClass() == x.getClass()
返回turex.clone().equals(x)
返回ture假设有一个Person
类,有眼睛(eye
字段)和性别(sex
字段),其中sex
是基本数据类型,eye
是引用数据类型
public class Person{
public static final int SEX_MAN = 0;
public static final int SEX_WOMAN = 0;
private int sex;
private Eye eye;
public Person shallowCopy(){
Person dest = new Person();
dest.sex = this.sex;
dest.eye = this.eye;
return dest;
}
public Person deepCopy(){
Person dest = new Person();
dest.sex = this.sex;
dest.eye = this.eye.deepCopy();
return dest;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getClass().getName() + "@" + Integer.toHexString(hashCode()))
.append(": { ")
.append("sex: ").append(sex).append(", ")
.append("eye: ").append(eye.toString())
.append(" }");
return buffer.toString();
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public Eye getEye() {
return eye;
}
public void setEye(Eye eye) {
this.eye = eye;
}
}
class Eye {
public static final String COLOR_BLACK = "black";
public static final String COLOR_BLUE = "blue";
private String color;
private int size;
public Eye(String color, int size){
this.color = color;
this.size = size;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public Eye deepCopy(){
return new Eye(this.color, this.size);
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getClass().getName() + "@" + Integer.toHexString(hashCode()))
.append(": { ")
.append("color: ").append(color).append(", ")
.append("size: ").append(size)
.append(" }");
return buffer.toString();
}
}
shalldowCopy为自定义的方法,在方法中,直接构造一个新对象,将源对象的每一个字段使用=
赋值给新对象中,调用shalldowCopy()方法即可完成浅拷贝
重写clone
方法,在类的clone
方法种直接调用super.clone()
,调用clone()方法即可完成浅拷贝
public class Person implements Cloneable {
public Person clone(){
Person dest = null;
try{
dest = (Person) super.clone();
} catch (CloneNotSupportedException e){
e.printStackTrace();
}
return dest;
}
}
deepCopy为自定义的方法,在方法中,直接构造一个新对象,对源对象的基本数据类型字段使用=
赋值给新对象中,对于引用数据类型使用deepCopy方法赋值,调用deepCopy()方法即可完成深拷贝
重写clone
方法,在类的clone
方法种调用super.clone()
,对于引用数据类型使用deepCopy方法赋值,调用clone()方法即可完成深拷贝
public class Person implements Cloneable {
public Person clone(){
Person dest = null;
try{
dest = (Person) super.clone();
dest.eye = dest.eye.deepCopy();
} catch (CloneNotSupportedException e){
e.printStackTrace();
}
return dest;
}
}
标签:col ide cat ring exce container tostring prot port
原文地址:https://www.cnblogs.com/myibu/p/12817405.html