代码生成(java拷贝对象)
时间: 2023-06-22 15:34:38 浏览: 192
在Java中,拷贝对象有两种方式:浅拷贝和深拷贝。
1. 浅拷贝
浅拷贝只复制对象的引用,而不是对象本身。这意味着,修改复制后的对象会影响原始对象。
可以使用Object类的clone()方法实现浅拷贝,但需要保证被拷贝对象实现了Cloneable接口。
示例代码:
```
public class Person implements Cloneable {
private String name;
private int age;
private List<String> hobbies;
public Person(String name, int age, List<String> hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
public Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
List<String> hobbies = new ArrayList<>();
hobbies.add("reading");
hobbies.add("running");
Person p1 = new Person("Tom", 20, hobbies);
Person p2 = p1.clone();
System.out.println(p1 == p2); // false
System.out.println(p1.getHobbies() == p2.getHobbies()); // true
}
}
```
2. 深拷贝
深拷贝会复制对象本身,而不是对象的引用。这意味着,修改复制后的对象不会影响原始对象。
可以使用Java自带的序列化和反序列化实现深拷贝。
示例代码:
```
public class Person implements Serializable {
private String name;
private int age;
private List<String> hobbies;
public Person(String name, int age, List<String> hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
public Person 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 (Person) ois.readObject();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
List<String> hobbies = new ArrayList<>();
hobbies.add("reading");
hobbies.add("running");
Person p1 = new Person("Tom", 20, hobbies);
Person p2 = p1.deepClone();
System.out.println(p1 == p2); // false
System.out.println(p1.getHobbies() == p2.getHobbies()); // false
}
}
```
以上是两种常见的对象拷贝方式,需要根据具体情况选择使用哪种方式。需要注意的是,如果要使用深拷贝,对象的类必须实现Serializable接口。
阅读全文