kirti kanodia
kirti kanodia

Reputation: 61

Can I have StringBuilder in an immutable class

If I create an immutable class. All the fields have to be final. If I use stringbuilder in that like this final StringBuilder s = new StringBuilder("Hello ");

, then the append function can append the value of the s and the class wont be immutable. Please advice.

Upvotes: 2

Views: 480

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500535

It's "shallow-immutable" in that you can't change the fields themselves, but it's not fully immutable - which means you lose pretty much all the benefits associated with immutability.

Basically to achieve immutability, all the constituent parts must either be naturally immutable, or sometimes you can get away with using something which is mutable but a) you constructed it, so nothing else has a reference to it; b) you never expose a reference to it; c) you never mutate it yourself.

For example, you can write an immutable type that uses java.util.Date (although I'd strongly recommend using java.time) - you'd just need to make sure that if you ever wanted to return a date from a method, you cloned it instead of returning the value of the field.

Upvotes: 6

Related Questions