各种拷贝方法比较

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;
    }  
}  

 

转载于:https://www.cnblogs.com/tonggc1668/p/6554887.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值