gpt4 book ai didi

java - java中浅拷贝和深拷贝演示的例子

转载 作者:行者123 更新时间:2023-12-02 08:04:20 25 4
gpt4 key购买 nike

// 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
*/

我已经写好了示例,请看看我是否遗漏了任何内容。我必须提供一个有关它的演示,并希望它尽可能简单。如果我可以使其变得更简单,请告诉我。我在他们更改值或克隆对象的地方提供了引号。

最佳答案

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

public class Book{
private String title;
private Author author;
...
}
public class Author{
private String name;
...
}

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

关于java - java中浅拷贝和深拷贝演示的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8406534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com