各种拷贝方法比较

package com.yd.wmsc.copy;

import java.util.*;

public class TestCopy {
public static void main(String[] args) throws CloneNotSupportedException {
    Name name = new Name("John", "Chen");  
    Person person = new Person(name, 28); 
    
    Person copyOfPerson = (Person)person.clone();  
     
    /*
    List<Object> srclst = new ArrayList<Object>();
    List<Object> destlst = new ArrayList<Object>();
    
    srclst.add(person);
    destlst.add(null);
    // copy into dest list
    Collections.copy(destlst, srclst); 
    System.out.println(destlst.size());
    Person copyOfPerson = (Person)destlst.get(0);*/
    
    
    name.setFirstName("Johnny");  
    name.setLastName("Qin");  
    person.setAge(29);  
    System.out.println(copyOfPerson.getName().getFirstName() + " " +  
            copyOfPerson.getName().getLastName() +   
            " " + copyOfPerson.getAge());
    //浅拷贝Johnny Qin 28
    //深拷贝John Chen 28
    //Collections.copy Johnny Qin 29
    
}
}
package com.yd.wmsc.copy;

public class Name implements Cloneable {
    private String firstName;
    private String lastName;

    public Name(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;

    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
package com.yd.wmsc.copy;

public class Person implements Cloneable {  
    private Name name;  
    private int age;  
  
    
    public Person(Name name,int age){
        this.name = name;
        this.age = age;
        
    }
    
    protected Object clone() throws CloneNotSupportedException {  
        //浅拷贝
        //return super.clone();
        //深拷贝
        Person person = (Person)super.clone();
        person.setName((Name)person.getName().clone());
        return person;
    }

    public Name getName() {
        return name;
    }

    public void setName(Name name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }  
}  

 

posted @ 2017-03-15 16:26  tonggc1668  阅读(142)  评论(0编辑  收藏  举报