Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 909
Code Complete Avatar asked Jun 23 '26 11:06

Code Complete


1 Answers

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.

like image 126
talex Avatar answered Jun 25 '26 23:06

talex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!