gpt4 book ai didi

java - 我应该在 Java 中使用 Clone 方法吗?

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

我听说你应该在你的代码中避免它,但它是出于某种原因实现的,所以在某些情况下使用它实际上是一个好的(或不错的)选择,还是我应该总是尽量避免它?

最佳答案

Josh Bloch answered this perfectly:

If you've read the item about cloning in my book, especially if youread between the lines, you will know that I think clone is deeplybroken. There are a few design flaws, the biggest of which is that theCloneable interface does not have a clone method. And that means itsimply doesn't work: making something Cloneable doesn't say anythingabout what you can do with it. Instead, it says something about whatit can do internally. It says that if by calling super.clonerepeatedly it ends up calling Object's clone method, this method willreturn a field copy of the original.

But it doesn't say anything about what you can do with an object thatimplements the Cloneable interface, which means that you can't do apolymorphic clone operation. If I have an array of Cloneable, youwould think that I could run down that array and clone every elementto make a deep copy of the array, but I can't. You cannot castsomething to Cloneable and call the clone method, because Cloneabledoesn't have a public clone method and neither does Object. If you tryto cast to Cloneable and call the clone method, the compiler will sayyou are trying to call the protected clone method on object.

It's a shame that Cloneable is broken, but it happens. The originalJava APIs were done very quickly under a tight deadline to meet aclosing market window. The original Java team did an incredible job,but not all of the APIs are perfect. Cloneable is a weak spot, and Ithink people should be aware of its limitations.

关于java - 我应该在 Java 中使用 Clone 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26578517/

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