本文将简单介绍java中对象的浅拷贝和深拷贝知识点!
Java中通过对象的clone方法可以复制对象,而clone方法在Object里定义的,是一个protected类型的方法,只有实现了Cloneable(java.lang.Cloneable)接口,该类对象才能调用clone方法,否则抛出异常。
1.浅拷贝
对象经过浅拷贝,基本类型的属性会拷贝值,引用类型的属性会拷贝引用。因此修改引用类型的属性值会影响另一对象!
示例代码
package com.test;
public class ShallowCopyTest {
static class Country
{
String name;
Country(String name)
{
this.name = name;
}
}
static class Person implements Cloneable
{
String name;
int age;
Country country;
Person(String name, int age, Country country)
{
this.name = name;
this.age = age;
this.country = country;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
/**
* @param args
*/
public static void main(String[] args) {
Person zhangsan = new Person("zhangsan", 24, new Country("China"));
System.out.println("zhangsan - " + zhangsan.name + ":" + zhangsan.age + ":" + zhangsan.country.name);
try {
Person tom = (Person) zhangsan.clone();
System.out.println("tom - " + tom.name + ":" + tom.age + ":" + tom.country.name);
tom.name = "tom";
tom.age = 21;
tom.country.name = "USA";
System.out.println("----------after----------");
System.out.println("zhangsan - " + zhangsan.name + ":" + zhangsan.age + ":" + zhangsan.country.name);
System.out.println("tom - " + tom.name + ":" + tom.age + ":" + tom.country.name);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
zhangsan - zhangsan:24:China
tom - zhangsan:24:China
----------after----------
zhangsan - zhangsan:24:USA
tom - tom:21:USA
2.深拷贝
对象经过深拷贝,基本类型的属性会拷贝值,引用类型所指向的对象内容也会拷贝一份。因此修改引用类型的属性值不会影响另一对象!
示例代码
package com.test;
public class DeepCopyTest {
static class Country implements Cloneable
{
String name;
Country(String name)
{
this.name = name;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
static class Person implements Cloneable
{
String name;
int age;
Country country;
Person(String name, int age, Country country)
{
this.name = name;
this.age = age;
this.country = country;
}
@Override
public Object clone() throws CloneNotSupportedException {
Person obj = (Person) super.clone();
obj.country = (Country) this.country.clone();
return obj;
}
}
/**
* @param args
*/
public static void main(String[] args) {
Person zhangsan = new Person("zhangsan", 24, new Country("China"));
System.out.println("zhangsan - " + zhangsan.name + ":" + zhangsan.age + ":" + zhangsan.country.name);
try {
Person tom = (Person) zhangsan.clone();
System.out.println("tom - " + tom.name + ":" + tom.age + ":" + tom.country.name);
tom.name = "tom";
tom.age = 21;
tom.country.name = "USA";
System.out.println("----------after----------");
System.out.println("zhangsan - " + zhangsan.name + ":" + zhangsan.age + ":" + zhangsan.country.name);
System.out.println("tom - " + tom.name + ":" + tom.age + ":" + tom.country.name);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
打印结果
zhangsan - zhangsan:24:China
tom - zhangsan:24:China
----------after----------
zhangsan - zhangsan:24:China
tom - tom:21:USA