gpt4 book ai didi

java - 复制构造函数与可克隆。为什么我不应该考虑 Cloneable?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:08:56 25 4
gpt4 key购买 nike

我正在读这个answer他提到了一个link ,作者解释了为什么我们不应该使用 Cloneable。但是,仍然怀疑那里所说的内容

If I have an array of Cloneable, you would think that I could run down that array and clone every element to make a deep copy of the array, but I can't. You can not cast something to Cloneable and call the clone method, because Cloneable doesn't have a public clone method and neither does Object. If you try to cast to Cloneable and call the clone method, the compiler will say you are trying to call the protected clone method on object.

但是,我做到了

        Init s = Init.getInstance(); // getting instance
int count=0;
Cloneable[] v = new Cloneable[5]; // creating array
Init x = s;
Init y = new Init(s);
try {
while (count < 5) {
v[count++] = (Cloneable) s.clone(); // casting it.
}

s.setClassName("Example");
System.out.println(((Init) v[2]).getClassName()); // Displaying.
} catch (CloneNotSupportedException ex) {
ex.printStackTrace();
}

我能够创建 Cloneable 数组并且我做了作者所说的会导致错误的事情或者我误解了作者的陈述吗?任何人,请帮助我理解选择 Copy Constructor 而不是 Cloneable 的原因。

最佳答案

您不是将 s 转换为 Cloneable,然后对其调用 clone()

相反,您正在调用 s.clone(),然后将结果转换为 Clonable。您能够这样做是因为 sInit 类型并且 Init 具有 public clone() 方法。

改为执行此操作,您会发现编译器大喊大叫,

 v[count++] =  ((Cloneable) s).clone();

现在假设你想克隆一个数组(你显然只知道它是一个 Cloneable 数组。这意味着你不知道它是实际的类型。

Cloneable[] cloneArray = new Cloneable[5];
cloneArray[i] = new Init(); // Let's say it's initialized with different type objects but all `Cloneable`.

for (Cloneable object : cloneArray) {
object.clone(); // Compiler wont allow it. And you don't know what type it is.
}

因此,您基本上无法深度克隆 Cloneable 数组。

关于java - 复制构造函数与可克隆。为什么我不应该考虑 Cloneable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31603227/

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