Search code examples
javaclonestringbuilderstringbuffercloneable

What prevents from making Cloneable a mutable object like StringBuilder?


It is a bad idea to make an immutable object Cloneable. This is why String is not Cloneable. Immutable BigInteger and BigDecimal are also not Cloneable.

But mutable StringBuilder and StringBuffer cannot be cloned!

What is the reason behind that desicion?

Yes, I can use "copy constructor" new StringBuilder(CharSequence seq) but what is the design principle/reasoning to supply a copy constructor and prohibit cloning?


Solution

  • Because Cloneable was mistake from beginning.

    • It have difficult to use interface (you have to cast result back)
    • Unclean semantic (will it be deep clone or shallow clone?)
    • It is difficult to customize

    All of these made this interface unpopular.

    So answer is: no one wants it.

    EDIT

    If you want to know why it will be bad idea to implement Cloneable in StringBuilder: Cloneable have shallow-copy semantic and this make difficult to maintain invariants (this is generic problem with shallow copy of mutable objects). For example there is optimizations in toString which will be broken in case we clone it.