RFR(m): 8177290 add copy factory methods for unmodifiable List, Set, Map

Stuart Marks stuart.marks at oracle.com
Wed Nov 29 23:49:41 UTC 2017



On 11/29/17 10:09 AM, Martin Buchholz wrote:
> Guava's "immutable collections" are very popular 
> https://github.com/google/guava/wiki/ImmutableCollectionsExplained and it's
> not a good idea to fight their advertised notion of "immutable".
> 
> No generic container class can promise s'marks-style immutability (until 
> valhalla perhaps?) so it's not that useful a concept in this domain. We like
> to think of Optional as an immutable value based class but you can't stop
> anyone who really wants to mutate the contained element from creating an 
> Optional<AtomicReference<Object>>

Sure, you can't prevent anybody from doing something like this.

The big problem with "immutable" is that to many people it seems to imply what 
I'd call "persistent". That is, modification operations will modify and return a 
new data structure, preserving the old one (unmodified), often with structural 
sharing. A web search for "immutable data structure" matches this. Java is the 
outlier in trying to define "immutable" as meaning "throws 
UnsupportedOperationException" on modification.

I really think "unmodifiable" is the better word here.

> We could do a better job of clarifying consequences of element mutation.
> E.g. do we ever say that hash based collections/maps are broken if elements
> are ever mutated in such a way that their hash code changes while they are in
> the collection/map?

Not exactly, but Set has the following in the class doc:

> Note: Great care must be exercised if mutable objects are used as set
> elements. The behavior of a set is not specified if the value of an object is
> changed in a manner that affects equals comparisons while the object is an
> element in the set. A special case of this prohibition is that it is not
> permissible for a set to contain itself as an element.

(Map has something similar.) There isn't anything in SortedSet/SortedMap that 
talks about mutation vs. its effect on the Comparator-imposed total ordering. 
Perhaps there should be.

s'marks


More information about the core-libs-dev mailing list