Java 当我们可以使用=运算符复制对象时,为什么要使用clone()?

Java 当我们可以使用=运算符复制对象时,为什么要使用clone()?,java,Java,Clone()用于对象的精确副本。像这样 B s2=(B)s1.clone(); 但我们也可以使用如下语法复制对象# 在这两种情况下,输出是相同的,那么为什么要使用clone() 因为当您编写b1=b2时,您只需创建对同一对象的另一个引用 B b1 = new B(); // b1 is a reference to the B object B b2 = b1; // b2 is a new reference to the same B object B b3 =

Clone()用于对象的精确副本。像这样

B s2=(B)s1.clone();  
但我们也可以使用如下语法复制对象#

在这两种情况下,输出是相同的,那么为什么要使用clone()


因为当您编写
b1=b2
时,您只需创建对同一对象的另一个引用

B b1 = new B();    // b1 is a reference to the B object
B b2 = b1;         // b2 is a new reference to the same B object
B b3 = (B)b1.clone(); // b3 is a reference to the new B object (total two B objects in memory) 

因为当您编写
b1=b2
时,您只需创建对同一对象的另一个引用

B b1 = new B();    // b1 is a reference to the B object
B b2 = b1;         // b2 is a new reference to the same B object
B b3 = (B)b1.clone(); // b3 is a reference to the new B object (total two B objects in memory) 
s2=s1
不复制对象。它只是将一个附加变量指向同一对象

B b1 = new B();    // b1 is a reference to the B object
B b2 = b1;         // b2 is a new reference to the same B object
B b3 = (B)b1.clone(); // b3 is a reference to the new B object (total two B objects in memory) 
如果您随后执行
s1.setFoo(“bar”)
,将影响“两个”对象(因为只有一个对象)。

s2=s1
不会复制该对象。它只是将一个附加变量指向同一对象

B b1 = new B();    // b1 is a reference to the B object
B b2 = b1;         // b2 is a new reference to the same B object
B b3 = (B)b1.clone(); // b3 is a reference to the new B object (total two B objects in memory) 

如果随后执行s1.setFoo(“bar”),将影响“两个”对象(因为只有一个对象)。

此行不会克隆对象:

B s2=s1;
它只需创建第二个引用同一对象的变量
s2

B b1 = new B();    // b1 is a reference to the B object
B b2 = b1;         // b2 is a new reference to the same B object
B b3 = (B)b1.clone(); // b3 is a reference to the new B object (total two B objects in memory) 
当您在打印任何一项之前尝试修改
s2
时,可以看到差异:

B s1 = new B(101, "amit");

B s2 = s1;
s2.name="newName";

System.out.println(s1.rollno + " " + s1.name);
System.out.println(s2.rollno + " " + s2.name);
这段代码将打印
newName
作为两行的名称,因为实际上只有一个对象被两个变量引用


但是,如果将
bs2=s1
替换为
bs2=s1.clone()
,则会打印两个不同的名称,因为创建了对象的实际副本。

此行不会克隆对象:

B s2=s1;
它只需创建第二个引用同一对象的变量
s2

B b1 = new B();    // b1 is a reference to the B object
B b2 = b1;         // b2 is a new reference to the same B object
B b3 = (B)b1.clone(); // b3 is a reference to the new B object (total two B objects in memory) 
当您在打印任何一项之前尝试修改
s2
时,可以看到差异:

B s1 = new B(101, "amit");

B s2 = s1;
s2.name="newName";

System.out.println(s1.rollno + " " + s1.name);
System.out.println(s2.rollno + " " + s2.name);
这段代码将打印
newName
作为两行的名称,因为实际上只有一个对象被两个变量引用

但是,如果将
bs2=s1
替换为
bs2=s1.clone()
,则它将打印两个不同的名称,因为创建了对象的实际副本