本文介绍了为什么人们如此害怕使用clone()(在collection和JDK类上)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我多次争论使用clone()并不是一个坏习惯.是的,我知道论点. Bloch说这很糟糕.他确实做到了,但是他说实现clone()是不好的.另一方面,使用克隆,尤其是如果由受信任的库(例如JDK)正确实现了克隆,就可以了.

A number of times I've argued that using clone() isn't such a bad practice. Yes, I know the arguments. Bloch said it's bad. He indeed did, but he said that implementing clone() is bad. Using clone on the other hand, especially if it is implemented correctly by a trusted library, such as the JDK, is OK.

昨天,我讨论了有关我的答案仅表明将clone()用作ArrayList是可以的(我猜对此没有任何投票).

Just yesterday I had a discussion about an answer of mine that merely suggests that using clone() for ArrayList is OK (and got no upvotes for that reason, I guess).

如果我们查看ArrayList@author,我们会看到一个熟悉的名字-乔什·布洛赫(Josh Bloch).因此,ArrayList(和其他集合)上的clone()很好(只需看一下它们的实现).

If we look at the @author of ArrayList, we can see a familiar name - Josh Bloch. So clone() on ArrayList (and other collections) is perfectly fine (just look at their implementations).

Calendar以及大多数java.langjava.util类都适用.

Same goes for Calendar and perhaps most of the java.lang and java.util classes.

所以,请给我一个理由为什么不对JDK类使用 clone()?

So, give me a reason why not to use clone() with JDK classes?

推荐答案

  • 给出一个ArrayList引用,您将需要进行getClass检查,以确保它不是JDK类的子类.然后什么?潜在的子类不能被信任.大概子类在某种程度上会有不同的行为.
  • 它要求引用比List更具体.有人不介意,但是大多数人认为那是个坏主意.
  • 您将不得不处理演员表,这是一个不安全的演员.
    • Given an ArrayList reference, you would need a getClass check to check that it is not a subclass of the JDK class. And then what? Potential subclasses cannot be trusted. Presumably a subclass would have different behaviour in some way.
    • It requires that the reference is more specific than List. Some people don't mind that, but the majority opinion is that that is a bad idea.
    • You'll have to deal with a cast, an unsafe cast at that.
    • 这篇关于为什么人们如此害怕使用clone()(在collection和JDK类上)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 05:29