1.对象实现拷贝方法,对象内部的基本类型不用管,不涉及到地址
对象类型继续实现拷贝方法:
package calmcalmcalm;
import lombok.Data;
import java.util.Arrays;
import java.util.List;
/**
* @author jinsong.Liang
* @Description
* @date 2019/4/28 18:10
*/
public class deepCopy2 {
public static void main(String[] args) throws CloneNotSupportedException {
Person person = new Person();
person.setName("小李");
person.setAge(20);
GrandParent one = new GrandParent("小李爷爷", 80);
GrandParent another = new GrandParent("小李奶奶", 77);
person.setGrandParents(Arrays.asList(one,another));
Person person2 = (Person) person.clone();
person2.setName("小松");
person2.setAge(21);
person2.setGrandParents(Arrays.asList(new GrandParent("小松爷爷",81),new GrandParent("小松奶奶",77)));
System.out.println(person+" "+person2);
}
}
@Data
class Person implements Cloneable{
private String name;
private int age;
private List<GrandParent> grandParents;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
@Data
class GrandParent implements Cloneable{
private String name;
private int age;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public GrandParent() {
}
public GrandParent(String name, int age) {
this.name = name;
this.age = age;
}
}
2.使用序列化 直接写入流中 再从流中读取 用到了
ByteArrayOutputStream ByteArrayInputStream
ObjectOutputStream ObjectInputStream:
package calmcalmcalm;
import lombok.Data;
import java.io.*;
import java.util.Arrays;
import java.util.List;
/**
* @author jinsong.Liang
* @Description 串行化实现深拷贝
* @date 2019/4/28 17:27
*/
public class deepCopy {
public static void main(String[] args) {
Student stu = new Student();
stu.setName("小李");
Parent one = new Parent("小李爸", 40);
Parent another = new Parent("小李妈", 37);
stu.setParents(Arrays.asList(one, another));
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(stu);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream is = new ObjectInputStream(in);
Student object = (Student) is.readObject();
object.setName("小松");
object.setParents(Arrays.asList(new Parent("小松爸", 40), new Parent("小松妈", 36)));
System.out.println(object + " " + stu);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Data
class Student implements Serializable {
private static final long serialVersionUID = 1225886679045375224L;
private String name;
private List<Parent> parents;
}
@Data
class Parent implements Serializable {
private static final long serialVersionUID = 3295359707477734908L;
private String name;
private int age;
public Parent() {
}
public Parent(String name, int age) {
this.name = name;
this.age = age;
}
}
Idea出现中文乱码:字符编码设置为GBK即可 convert方式而非reload方式
关于编码:
GBK存储:中文俩字节 英文一个字节
UTF8 UTF16 UTF32是根据尽可能使用分配空间和直接分配较大的空间而产生的不同编码方式
UTF8存储 1-6字节 UTF16介于UTF8 和 UTF32之间 2字节或4字节 UTF32是4个字节存储