一、Cloneable接口
Cloneable只是一个标记接口,只有实现了这个接口,才能在类中重写clone方法,然后通过类调用clone完成功能实现,如果不实现这个接口,则会抛出CloneNotSupportedException(克隆不被支持)异常
1、浅克隆
首先创建Student类实现Cloneable接口,重写clone方法,clone默认返回Object类,所以我们在返回时就强转为Student类
// 省略构造方法,get,set方法
class Student implements Cloneable{
private String name;
private int age;
private School school;
@Override
protected Student clone() throws CloneNotSupportedException {
return (Student)super.clone();
}
创建School类
// 省略构造方法
class School{
private String name;
private String address;
}
测试类调用
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
School school = new School("清华大学","北京");
Student student = new Student("lisa",22,school);
Student student1 = student.clone();
System.out.println(student);
System.out.println(student1);
System.out.println(student.getSchool());
System.out.println(student1.getSchool());
student.getSchool().setName("北京大学");
System.out.println(student.getSchool().getName());
System.out.println(student1.getSchool().getName());
}
}
结果
Student@4554617c
Student@74a14482
School@1540e19d
School@1540e19d
北京大学
北京大学
可以看出student与student1的hashcode不同,也就是说clone方法并不是把student的引用赋予student1,而是在堆中重新开辟了一块空间,将student复制过去,将新的地址返回给student1
但是s1中stu的hashcode与s2中stu的hashcode相同,也就是这两个指向了同一个对象,修改s2中的stu会造成s1中stu数据的改变。但是修改s2中的基本数据类型与Stirng类型时,不会造成s1中数据的改变,基本数据类型例如int,在clone的时候会重新开辟一个四个字节的大小的空间,将其赋值。而String则由于String变量的唯一性,如果在s2中改变了String类型的值,则会生成一个新的String对象,对之前的没有影响。
2、深克隆
我们让School类实现Cloneable接口,重写其clone方法,然后修改Student类的clone方法
@Override
protected Student clone() throws CloneNotSupportedException {
Student newStudent = (Student)super.clone();
newStudent.school = newStudent.school.clone();
return newStudent;
}
结果
Student@4554617c
Student@74a14482
School@1540e19d
School@677327b6
北京大学
清华大学
这时候School类已经不相同了
一、Serializable接口
Serializable 是 java.io 包中定义的、用于实现Java类的序列化操作而提供的一个语义级别的接口。Serializable 序列化接口没有任何方法或者字段,只是用于标识可序列化的语义。实现了 Serializable 接口的类可以被 ObjectOutputStream 转换为字节流,同时也可以通过 ObjectInputStream 再将其解析为对象。我们可以在需要写入文件、写入数据库,进行网络传输时使用这个接口
创建需要被序列化的实体类
// 省略构造方法,toString方法
class Student implements Serializable {
private String name;
private int age;
测试类
public class Test {
public static void main(String[] args) {
Student student = new Student("lisa", 22);
writeObject(student);
Student student1 = readObject();
System.out.println(student1);
}
// 将类写入文件
public static void writeObject(Student student){
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(new FileOutputStream("1.txt"));
oos.writeObject(student);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 从文件中读取类
public static Student readObject(){
Student student = null;
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("1.txt"));
student = (Student) ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException classNotFoundException) {
classNotFoundException.printStackTrace();
}
return student;
}
}
结果
Student{name='lisa', age=22}