浅拷贝:对象中的基本类型进行值拷贝,引用类型对引用地址进行拷贝。
深拷贝:对象中的基本类型和引用类型对应的值都进行拷贝。
注意:不管是深拷贝还是浅拷贝,拷贝之后,两个对象的hashcode 不同,而且equels() 返回也是false。
java 实现浅拷贝: 必须实现Cloneable 接口,并且重写Object 的clone()
public class ShallowCopy implements Cloneable {
private String name;
private int age;
public void hashMapCopy() {
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Object> map1 = new HashMap<String, Object>(map);
}
/**
* 浅拷贝,且必须要实现Cloneable接口
* *
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "ShallowCopy{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
java实现深拷贝:通过继承Serializable接口,然后使用InputStream 和OutputStream 构造一个新的对象
public class DeepCopy {
public static Object deepCopy(Object obj) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(bo);
objectOutputStream.writeObject(obj);
ByteArrayInputStream bio = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(bio);
return objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
User user = new User("zhangsan", 23);
User user1 = (User) DeepCopy.deepCopy(user);
System.out.println("user hashcode:" + user.hashCode());
System.out.println("user1 hashcode:" + user1.hashCode());
System.out.println("==" + user.equals(user1));
System.out.println("user:" + user.toString());
System.out.println("user1:" + user1.toString());
/**
运行结果:
user hashcode:1426979015
user1 hashcode:1743450717
==false
user:User{name='zhangsan', age=23}
user1:User{name='zhangsan', age=23}
*/
}
}
class User implements Serializable {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}