首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >java中的浅拷贝和深拷贝演示示例

java中的浅拷贝和深拷贝演示示例
EN

Stack Overflow用户
提问于 2011-12-07 04:40:23
回答 1查看 1.9K关注 0票数 0
代码语言:javascript
复制
// shallow copy example
public class a
{
    public static void main(String[] args) throws CloneNotSupportedException
    {
        b x = new b(2);
        System.out.println(x.i[0]); // previous value for object x
        System.out.println(x.k);
        b y =(b)x.clone(); // y shallow clone of object x
        y.i[0] = 10; y.k = 999; // changed values in object y
        System.out.println(y.i[0]); // values of y after change
        System.out.println(y.k);

        System.out.println(x.i[0]); // values of x after change     
        System.out.println(x.k);
        System.out.println(x.getClass() == y.getClass()); // both objects belong to same class
        System.out.println(x == y); // both objects are different, they are not the same
    }
}

class b implements Cloneable
{
    public int i[] = new int[1];
    int k;

    public Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }

    b(int j)
    {
        super();
        i[0] = j;
        k = j + 2;
    }
}

/*output

2
4
10
999
10
4
true 
false
*/
//*********************************************************************
//deep copy example

public class a
{     
    public static void main(String[] args) throws CloneNotSupportedException 
    {  
        b x = new b(2);
        System.out.println(x.i[0]); // object x values before change
        System.out.println(x.k);

        b y = (b)x.clone(); // deep clone y of object x

        System.out.println(y.i[0]); // values of object y
        System.out.println(y.k);

        System.out.println(x.i[0]); // values of object x after changing the values of the members in object y in clone method  
        System.out.println(x.k);
        System.out.println(x.getClass() == y.getClass());
        System.out.println(x==y);
    }
}

class b implements Cloneable
{
    public int i[] = new int[1];
    int k;

    public Object clone()throws CloneNotSupportedException
    {
        b t = new b(6);
        return t;
    }

    b(int j)
    {
        i[0] = j;
        k = j+2;
    }
}

/*

2
4
6
8
2
4
true 
false
*/

我已经写了例子,请看看我是否遗漏了什么,我必须提供一个关于它的演示,并希望它像possible.Do一样简单,让我知道我是否可以让它更简单。我提供了引号,无论它们在哪里改变了值或对象正在被克隆。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-12-07 07:00:19

演示的黄金提示:使用有意义的类名和变量名,并使示例更加具体。例如,使用Book类和Author

代码语言:javascript
复制
public class Book{
  private String title;
  private Author author;
...
}
public class Author{
  private String name;
  ...
}

使用getter/setter (甚至是公共字段),您可以对Book实例进行深度/浅层克隆,并演示当您更改Author的名称时会发生什么变化。与您所做的完全相同,但更容易告诉读者,也更容易让读者理解,因为每个人都知道什么是一本书和作者,并且不需要查看代码来遵循您的解释

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8406534

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档