gpt4 book ai didi

java - 使用克隆或使用构造函数并分配哪一种更有效

转载 作者:行者123 更新时间:2023-11-30 03:14:55 25 4
gpt4 key购买 nike

我有一个链接列表,我想复制该链接列表。克隆运行速度是否比创建新实例然后为其赋值更快?例如我有

LinkedList<MyClass> list = new LinkedList<MyClass>();
list.add(instance1);
list.add(instance2);

使用克隆:

LinkedList<MyClass> list2 = list.clone();

使用构造函数:

LinkedList<MyClass> list2 = new LinkedList<MyClass>();
for(MyClass myclass : list){
list2.add(myclass);
}

最佳答案

最好是使用浅复制构造函数。您编写了使用构造函数,而不是使用。您正在循环播放它。

我建议使用

List<MyClass> list2 = new LinkedList<MyClass>(list);

偶数Josh Bloch suggest the same

The truth of the matter is that you don't provide any capability to your clients by implementing Cloneable and providing a public clone method other than the ability to copy. This is no better than what you get if you provide a copy operation with a different name and you don't implement Cloneable. That's basically what you're doing with a copy constructor. The copy constructor approach has several advantages, which I discuss in the book. One big advantage is that the copy can be made to have a different representation from the original. For example, you can copy a LinkedList into an ArrayList.

关于java - 使用克隆或使用构造函数并分配哪一种更有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32879707/

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