package design;
public class Student implements Cloneable {
private String name;
private int age;
private String sex;
public Student() {
}
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Student s = null;
try {
s = (Student) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return s;
}
}
Student student = new Student("Name",15,"man");
List<Student> list=new ArrayList<>(10);
//利用传统的方式
for (int i = 0; i < 10; i++) {
student.setAge(i);
list.add(student);
}
for (Student student1 : list) {
System.out.print(student.getAge()+"|");
}
输出结果:
9|9|9|9|9|9|9|9|9|9|
利用浅克隆的方式:
Student student = new Student("Name",15,"man");
List<Student> list=new ArrayList<>(10);
//利用传统的方式
for (int i = 0; i < 10; i++) {
Student s1= (Student) student.clone();
s1.setAge(i);
list.add(s1);
}
for (Student student1 : list) {
System.out.print(student1.getAge()+"|");
}
输出结果:
0|1|2|3|4|5|6|7|8|9|
本例中用的是浅克隆的方式 ,基本数据类型和String类型的变量都可以直接复制其值,但是引用数据类型不能复制,如果对象中有引用数据类型,它实际上只是将内存地址复制下来了,要想实现真正的引用数据类型的复制,要用到深克隆的方式。
深克隆有两种方式:
第一种是重写 object的clone方法
第二种是利用序列化。
但是在实际的开发中,我们推荐使用序列化的方式来完成深克隆。
package design;
import java.io.*;
public class School {
private String schoolName;
private Student student;
public School(String schoolName, Student student) {
this.schoolName = schoolName;
this.student = student;
}
public School() {
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
@Override
public String toString() {
return "School{" +
"schoolName='" + schoolName + '\'' +
", student=" + student +
'}';
}
//提供深克隆的方法
public Object deepCopy() {
//创建流对象、
//输出流
ByteArrayOutputStream bos = null;
//对象输出流
ObjectOutputStream oos = null;
//输入流
ByteArrayInputStream bis = null;
//对象输入流
ObjectInputStream ois = null;
//第一步 序列化操作
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
//把当前对象以对象流的方式输出
oos.writeObject(this);
//反序列化
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
School school = (School) ois.readObject();
return school;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
System.out.println(e.getMessage());
return null;
}finally {
//开闭流
try {
bos.close();
oos.close();
bis.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}