Why people are so afraid of using clone() (on collection and JDK classes)?

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

  • 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.

Leave a Comment