Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical example for Immutable class

It is obvious that immutability increases the re-usability since it creates new object in each state change.Can somebody tells me a practical scenario where we need a immutable class ?

like image 552
Eshan Sudharaka Avatar asked Dec 19 '25 23:12

Eshan Sudharaka


1 Answers

Consider java.lang.String. If it weren't immutable, every time you ever have a string you want to be confident wouldn't change underneath you, you'd have to create a copy.

Another example is collections: it's nice to be able to accept or return a genuinely immutable collection (e.g. from Guava - not just an immutable view on a mutable collection) and have confidence that it won't be changed.

Whether those count as "needs" or not, I don't know - but I wouldn't want to develop without them.

like image 174
Jon Skeet Avatar answered Dec 21 '25 13:12

Jon Skeet



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!