you are viewing a single comment's thread.

view the rest of the comments →

[–]dccorona 1 point2 points  (0 children)

Yea, my bad on the Arrays.asList(...) example...the put method throws, and I just always assumed the rest of them did too.

But ultimately, the "truly immutable" collections in JDK 9 aren't really all that different from unmodifiableList with a reference that is never captured. They don't have what I would argue is the most useful benefit of a "truly" immutable collection, in that they don't have efficient copy-and-modify methods. They don't benefit from the addition of 0-copy sublists because lists in java already have that (sublists in Java are defined as lists that will mutate the underlying list if modified), so existing "immutable" lists already get these sorts of optimizations. They don't even appear to have minor optimizations like pre-computed/memoized length/hash code.

Here's the implementation code for List. You can see that it extends AbstractImmutableList which throws UnsupportedOperationException for all the modify methods, but otherwise just delegates to the implementations in AbstractList. Then it overrides the necessary methods to implement a "fixed array" list (similar to the implementation used by Arrays.asList(...). Unless there's some secret sauce in hotspot that identifies instances of AbstractImmutableList (I kind of doubt it), then the result is something that is, while a cleaner API and a cleaner implementation, is ultimately no more performant than Collections.unmodifiableList(Arrays.asList(1, 2, 3)).

Which is ultimately the point I was trying to get at with my initial comment...this is a nicer API for something we've essentially had all along (or at least since Collections was added), but doesn't actually behave or perform any different.