java怎么实现对象克隆

47次阅读
没有评论

共计 1761 个字符,预计需要花费 5 分钟才能阅读完成。

在 Java 中,可以通过两种方式来实现对象克隆:浅拷贝和深拷贝。

  1. 浅拷贝:使用 Object 类的 clone() 方法进行对象的浅拷贝。浅拷贝会创建一个新的对象,将原始对象的非静态字段的值复制到新对象中,对于引用类型的字段,复制的是引用而不是对象本身。如果原始对象中的字段是可变的,修改新对象中的字段会影响原始对象,反之亦然。

例如:

public class MyClass implements Cloneable {
private int intValue;
private String stringValue;
public MyClass(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
@Override
public Object clone() throws CloneNotSupportedException {return super.clone();
}
public static void main(String[] args) {MyClass obj1 = new MyClass(10, "Hello");
try {MyClass obj2 = (MyClass) obj1.clone();
System.out.println(obj1 == obj2); // false
System.out.println(obj1.intValue == obj2.intValue); // true
System.out.println(obj1.stringValue == obj2.stringValue); // true
} catch (CloneNotSupportedException e) {e.printStackTrace();
}
}
}
  1. 深拷贝:通过实现 Serializable 接口以及使用序列化和反序列化的方式实现对象的深拷贝。深拷贝会创建一个新的对象,将原始对象及其引用的对象都复制到新对象中,新对象与原始对象是完全独立的。

例如:

import java.io.*;
public class MyClass implements Serializable {
private int intValue;
private String stringValue;
public MyClass(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
public MyClass deepClone() 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 (MyClass) ois.readObject();}
public static void main(String[] args) {MyClass obj1 = new MyClass(10, "Hello");
try {MyClass obj2 = obj1.deepClone();
System.out.println(obj1 == obj2); // false
System.out.println(obj1.intValue == obj2.intValue); // true
System.out.println(obj1.stringValue == obj2.stringValue); // false
} catch (IOException | ClassNotFoundException e) {e.printStackTrace();
}
}
}

需要注意的是,要实现深拷贝,对象及其引用的对象都需要实现 Serializable 接口。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-21发表,共计1761字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)