Hacker News new | ask | show | jobs
by jtheory 4692 days ago
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.