Hacker News new | ask | show | jobs
by windust 4695 days ago
Not sure this is true. There is the concept of final fields, but that doesn't make objects immutable, and thus even when declaring object finals (or arrays) you can pretty easily shoot yourself in the foot by mutating them in-place.
1 comments

For immutable collections, guava is helpful.
It is -- but you still do have to be aware if the objects in your collection are also immutable... if so, you may end up with an "immutable" list of 5 objects, and down the line it will still have those 5 objects, but the objects themselves may have completely different internal data.

Referring partly to your parent comment... it's instructive to look at the String implementation.

It's immutable, but they have to jump through a few hoops to do it properly... internally, a String has a private char array. An array is not immutable, so the code has to be very careful to never expose that char array externally.

Because of that, calling toCharArray() will copy the internal array and return the copy -- that one's fairly obvious. But less obviously, a String constructed with a char array must also make a copy... otherwise the calling code might then modify the array after creating the String with it.

So sure, immutable objects are possible, and widely encouraged in Java, but they're easy to do wrongly/incompletely.