对象的克隆
1.对象的浅克隆
对象浅克隆要注意的细节:
1.如果一个对象需要调用clone的方法克隆,那么该对象所属的类必须要实现Cloneable接口,并且重写clone方法。
2.Cloneable接口只不过是一个标识借口而已,没有任何方法。
3.对象的浅克隆就是克隆一个对象的时候,如果被克隆的对象中维护了另外一个类的对象,这时候只是克隆另外一个对象的地址,而没有把另外一个对象也克隆一份,简而言之,就是克隆和被克隆的对象拥有一个相同地址的对象。
package cn.itcast.copy; import java.io.Serializable; class Address implements Serializable{ String city; public Address(String city){ this.city = city; } } public class Person implements Cloneable,Serializable { int id; String name; Address address; public Person(int id, String name) { this.id = id; this.name = name; } public Person(int id, String name, Address address) { this.id = id; this.name = name; this.address = address; System.out.println("=======构造方法被调用了==="); } @Override public String toString() { return "ID"+ this.id+"姓名"+ this.name+"城市"+ address.city; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
package cn.itcast.copy; public class Demo1 { public static void main(String[] args) throws Exception { Address address = new Address("广州"); Person p1 = new Person(110,"马云",address); Person p2 = (Person) p1.clone(); //clone() 克隆了一个对象 p2.address.city ="长沙"; System.out.println("p1:"+p1); System.out.println("p2:"+ p2); } }
对象的深克隆
对象的深克隆就是利用对象的输入输出流把对象先写到文件上,然后再读取对象的信息,这个过程就作为对象的深克隆。
工具:
ObjectInputStream
ObjectOutputStream
实例及步骤:
package cn.itcast.copy; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Demo2 { public static void main(String[] args) throws IOException, ClassNotFoundException { Address address = new Address("广州"); Person p1 = new Person(110,"马云",address); writeObj(p1); Person p2 =readObj(); p2.address.city = "长沙"; System.out.println("p1:"+ p1); System.out.println("p2:"+ p2); } //再从文件中读取对象的信息 public static Person readObj() throws ClassNotFoundException, IOException{ FileInputStream fileInputStream = new FileInputStream("F:\\obj.txt"); //创建对象的输入流对象 ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); return (Person) objectInputStream.readObject(); } //先把对象写到文件上 public static void writeObj(Person p) throws IOException{ //建立一个文件的输出流对象 FileOutputStream fileOutputStream = new FileOutputStream("F:\\obj.txt"); //建立对象的输出流 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); //把对象写出 objectOutputStream.writeObject(p); //关闭资源 objectOutputStream.close(); } }