简体   繁体   English

使用.clone()方法和=符号克隆对象有什么区别?

[英]What is the difference between cloning the object with .clone() method and = sign?

I am really confused about what is the difference between .clone() method or simply putting the = sign between objects while trying to clone it. 我真的很困惑.clone()方法之间的区别是什么,或者在尝试克隆它时简单地在对象之间放置=符号。

Thank You. 谢谢。

If you create a new Dog: 如果你创建一个新狗:

Dog a = new Dog("Mike");

and then: 然后:

Dog b = a;

You'd have one Dog and two variables that reference the same Dog . 你有一只Dog和两个变量引用同一Dog Therefore doing: 因此做:

a.putHatOnHead("Fedora");

if (b.hasHatOnHead()) {
    System.out.println("Has a hat: " + b.getHatName());
}

Will print that the dog has a Fedora hat, because a and b reference the same dog. 将打印出狗有Fedora帽子,因为ab引用同一只狗。

Instead, doing: 相反,做:

Dog b = a.clone();

Now you have two dogs clones. 现在你有两只狗克隆。 If you put a hat on each dog: 如果你在每条狗上戴上帽子:

a.putHatOnHead("Rayden");
b.putHatOnHead("Fedora");

Each dog will have its own hat. 每只狗都有自己的帽子。

Let me try to explain you: 让我试着解释一下你:

Object obj = new Object();  //creates a new object on the heap and links the reference obj to that object

Case 1: 情况1:

Object obj2 = obj;  //there is only one object on the heap but now two references are pointing to it.

Case 2: 案例2:

Object obj2 = obj.clone(); //creates a new object on the heap, with same variables and values contained in obj and links the reference obj2 to it.

for more info on clone method, you can refer the java api documentation 有关clone方法的更多信息,可以参考java api文档

The = sign is the assignment operator in java. =符号是java中的赋值运算符。 Having a = b means "I assign to the variable a the value of variable b . If b is an object, then a = b makes a point to the object that b is pointing to. It does not copy the object, nor clone it. 具有a = b的意思是“我分配给变量a变量的值b 。如果b是一个对象,则a = b使得a指向该对象b指向,但复制的对象,也不克隆它。

If you want to clone an object you either have to do it by hand (ugly), or have to make the class that has to be clonable to implement Clonable then call clone() . 如果你想要克隆一个对象,你必须手工(丑陋),或者必须使必须克隆的类来实现Clonable然后调用clone()

The advantage on clone() over the "ugly" way is that with clone() it's the developer of the class to be cloned that defines how cloning has to be done in order to ensure that the copy is a legit and working copy. clone()对“丑陋”方式的优势在于, clone()是要克隆的类的开发者,它定义了如何进行克隆以确保副本是合法且有效的副本。

With = you are just giving the same object a different name. 使用=您只是给同一个对象一个不同的名称。 With .clone you are creating a new object that is a copy of the original one. 使用.clone您将创建一个新对象,该对象是原始对象的副本。

= creates a new reference to the same object. =创建对同一对象的新引用。 clone() creates a new physical object with the same attributes as the earlier one clone()创建一个具有与前一个相同属性的新物理对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM