使用 new
关键字创建对象和使用 clone()
创建对象有什么区别? ?内存分配有什么区别吗?
最佳答案
new
根据构造函数创建一个对象,而 clone()
创建一个新对象并使用原始对象的内容初始化字段。
我接受了,您阅读了 javadoc,所以让我带您看一个示例:
public class MyBaby implements Cloneable {
int age = 0;
String name = "Dolly";
List<String> list = new ArrayList<String>();
public static void main(String[] args) {
MyBaby originalBaby = new MyBaby();
originalBaby.setAge(1);
try {
// We clone the baby.
MyBaby clonedBaby = (MyBaby) originalBaby.clone();
// both babies now have: age 1, name "Molly" and an empty arraylist
originalBaby.setAge(2);
// originalBaby has age 2, the clone has age 1
originalBaby.setName("Molly");
// same goes for the String, both are individual fields
originalBaby.getList().add("addedString");
// both babies get the string added to the list,
// because both point to the same list.
System.out.println(clonedBaby.toString());
}
catch (CloneNotSupportedException e) {}
}
}
javadoc 说:
this method performs a "shallow copy" of this object, not a "deep copy" operation.
这解释了我们婴儿列表的行为:引用被复制,而不是被引用的元素,因此我们的复制是“浅”的
内存分配当然可以不同:
- 您可以在构造函数中初始化字段
- clone可以初始化一个字段,即一个数组
关于java - 使用 new 关键字创建对象与使用 clone 方法之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13206094/