标题:Java里浅克隆和深克隆区别
只看楼主
白衣柳相
Rank: 3Rank: 3
等 级:论坛游侠
威 望:1
帖 子:142
专家分:168
注 册:2016-12-23
结帖率:82.61%
已结贴  问题点数:20 回复次数:1 
Java里浅克隆和深克隆区别
百度了很多,看着特别晕,有人可以详细讲讲么,谢谢
package test;
/*
 * 原型设计模式:浅克隆、深克隆
 * 创建大量同一类对象,使用克隆:克隆比new效率更高
 * Cloneable:空接口,资格的标记
 * clone():属于Object类
 */
class Book implements Cloneable{
    private String name;
    private double price;
   
   
    public String getName() {
        return name;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Book(String name,double price){
        this.name=name;
        this.price=price;
    }
   
    @Override
    public String toString(){
        return name+":"+price;
    }
   
    @Override
    public Object clone() throws CloneNotSupportedException{
        return super.clone();
        
    }

}

class Student{
    private String name;
    private Book book;
}

public class CloneTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        Book b1 = new Book("luoweideshenlin",26);
        Book b2 = (Book)b1.clone();//不等价:b2=b1;
        b2.setName("pingfandeshijie");
        b2.setPrice(78);
        
        System.out.println(b1.toString());
        System.out.println(b2.toString());
        System.out.println(b1==b2);
    }

}
这个是浅克隆还是深克隆啊,,,,,,,
搜索更多相关主题的帖子: private String name price public 
2017-11-26 23:33
calix
Rank: 9Rank: 9Rank: 9
等 级:贵宾
威 望:28
帖 子:249
专家分:1442
注 册:2015-5-4
得分:20 
这个属于浅克隆,对于引用类型的数据只会拷贝一个应引用对象,实际指向相同的实例
class Book implements Cloneable {
    private String name;
    private double price;
    private List<String> attributes;//引用类型
....
public static void main(String[] args) throws CloneNotSupportedException {
    List<String> attributes = new ArrayList<>();
    attributes.add("attr1");

    Book b1 = new Book("luoweideshenlin", 26, attributes);
    Book b2 = (Book) b1.clone();//不等价:b2=b1;
    b2.setName("pingfandeshijie");
    b2.setPrice(78);
    b2.getAttributes().add("attr2");

    System.out.println(b1.toString());
    System.out.println(b2.toString());
    System.out.println(b1 == b2);
}
实际输出结果连个对象的attributes是相同的:
luoweideshenlin:26.0,[attr1, attr2]
pingfandeshijie:78.0,[attr1, attr2]
false
2017-12-02 11:24



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-482854-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.567208 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved