java如何复制物品
深拷贝与浅拷贝的区别
浅拷贝仅复制对象的引用,不复制实际数据,修改副本会影响原对象。深拷贝创建完全独立的新对象,包括所有嵌套对象,修改副本不影响原对象。
实现浅拷贝的方法
1. 使用 clone() 方法
类需实现 Cloneable 接口并重写 clone() 方法:
class Item implements Cloneable {
String name;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone(); // 默认浅拷贝
}
}
// 使用示例
Item original = new Item();
Item copy = (Item) original.clone();
2. 通过构造函数复制
直接在构造函数中传入原对象属性:
class Item {
String name;
Item(Item other) {
this.name = other.name;
}
}
// 使用示例
Item copy = new Item(original);
实现深拷贝的方法
1. 手动逐层复制
递归复制所有嵌套对象:
class Item implements Cloneable {
String name;
Nested nested;
@Override
public Object clone() throws CloneNotSupportedException {
Item copy = (Item) super.clone();
copy.nested = (Nested) nested.clone(); // 嵌套对象也需实现Cloneable
return copy;
}
}
2. 使用序列化(Serialization)
通过序列化与反序列化实现完全独立拷贝:
import java.io.*;
class Item implements Serializable {
String name;
Item deepCopy() throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (Item) ois.readObject();
}
}
第三方库工具
Apache Commons Lang
使用 SerializationUtils.clone() 实现深拷贝:

import org.apache.commons.lang3.SerializationUtils;
Item copy = SerializationUtils.clone(original);
注意事项
- 深拷贝需确保所有嵌套类均支持序列化或实现
Cloneable。 - 性能敏感场景慎用序列化,手动复制效率更高。
- 不可变对象(如
String)无需深拷贝,直接引用即可。






