1 实现cloneable
2 调用克隆返回 super.clone
public Person clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
3 a克隆a的副本A,改变a对A没有影响,但a中若有引用类型的数据如b,则改变a中的b会影响A中的b,b这是浅克隆
若想a中的b不会影响A中的b,则要改变2中的代码,手动设置
public Person clone() {
try {
Person person = (Person)super.clone();
List<String> newfriends = new ArrayList<String>();
for(String friend : this.getFriends()) {
newfriends.add(friend);
}
person.setFriends(newfriends);
return person;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
引自北风网-厉风行