色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

java淺拷貝和深拷貝代碼

錢淋西1年前9瀏覽0評論

Java中的拷貝可以分為淺拷貝和深拷貝,兩者的實現(xiàn)方式和效果不同。

淺拷貝:淺拷貝是指將對象的引用復制一份,并不會復制對象本身。也就是說,當原對象的值發(fā)生改變時,拷貝后的對象的值也會跟著改變。

public class Person {
private int age;
private String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person(18, "Tom");
Person person2 = (Person) person1.clone();
System.out.println("person1:" + person1.toString());
System.out.println("person2:" + person2.toString());
System.out.println("After change age:");
person1.setAge(20);
System.out.println("person1:" + person1.toString());
System.out.println("person2:" + person2.toString());
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}

深拷貝:深拷貝是指將對象本身也復制一份。這樣,即使原對象的值發(fā)生改變,拷貝后的對象的值也不會發(fā)生改變。

public class Person implements Cloneable {
private int age;
private String name;
private Listhobby;
public Person(int age, String name, Listhobby) {
this.age = age;
this.name = name;
this.hobby = hobby;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ListgetHobby() {
return hobby;
}
public void setHobby(Listhobby) {
this.hobby = hobby;
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person(18, "Tom", new ArrayList(Arrays.asList("reading", "running")));
Person person2 = (Person) person1.clone();
System.out.println("person1: " + person1.toString());
System.out.println("person2: " + person2.toString());
System.out.println("After change age:");
person1.setAge(20);
System.out.println("person1: " + person1.toString());
System.out.println("person2: " + person2.toString());
System.out.println("After change hobby:");
person1.getHobby().add("swimming");
System.out.println("person1: " + person1.toString());
System.out.println("person2: " + person2.toString());
}
@Override
protected Object clone() throws CloneNotSupportedException {
Person person = (Person) super.clone();
person.hobby = new ArrayList<>(hobby);
return person;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
", hobby=" + hobby +
'}';
}
}

注意:如果要深拷貝一個對象,那么對象的所有成員變量都要支持深拷貝。

下一篇php inclode