gpt4 book ai didi

java - 使用克隆进行深度复制

转载 作者:行者123 更新时间:2023-12-02 06:14:27 25 4
gpt4 key购买 nike

我有一个公司对象列表。我正在尝试克隆此列表:

public static List<Company> cloneList(List<Company> list) {
List<Company> clone = new ArrayList<Company>(list.size());
for(Company item: list) clone.add(item.clone());
return clone;
}

但是我的编译器说:

Multiple markers at this line
- The method add(Company) in the type List<Company> is not applicable for the arguments
(Object)

为什么不能使用clone()进行深层复制?

最佳答案

clone() 方法是在根类 Object 上定义的(请参阅 here )。它返回一个对象,因此,如果您在重写时没有将其返回类型更改为具体类,则必须将其转换为正确的类型,例如:

clone.add((Company) item.clone());

或者在类中使用协变返回类型定义 clone() 如下:

public class Company implements Cloneable {
// stuff ...

public Company clone() throws CloneNotSupportedException { /* do clone */ }
}

请注意,您必须重写克隆方法,因为它是在受可见性保护的情况下定义的。

By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method. [source]

另请参阅this其他选项的问题。

关于java - 使用克隆进行深度复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21624841/

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