I am not sure the defects of Immutable collections I understand is correct, so I list them in this answer. Hope someone corrects me here.
a): Comparing to Collections.unmodifiableXXX(), ImmutableXXX.copyOf() loses the source collection feature. For example, when a linkedList is put into ImmutableList.copyOf(), the ImmutableList is not linked anymore. Same as Tree based collection.
b): People think Collections.unmodifiableXXX just uses same reference of source collection, so once the source collection is changed, Collections.unmodifiableXXX is also changed. But my solution is to wrap a source collection into a temp collection which is passed to ImmutableXXX.copyOf(). See code below:
List<String> l = new ArrayList<String>();
List<String> unmodifiableList = Collections.unmodifiableList(l);
ImmutableList<String> immutableList= ImmutableList.copyOf(l);
l.add("a");//unmodifiableList is also added "a", immutableList not.
/*My solution as follows:
So unmodifiableList2 is also immutable as ImmutableList.copyOf(l) does*/
List<String> unmodifiableList2= Collections.unmodifiableList(new ArrayList(l));
What's your understanding of Immutable collection? Thanks!
Nothing you have mentioned is a "defect".
a) It doesn't matter at all that an
ImmutableList
is no longer a linked list. The only advantages of a linked list over an array-based list involve adding and removing elements (removing primarily). You can't add to or remove from an immutable list, so array-based is preferable for its fast random access as well as memory efficiency.For something like
TreeSet
, there are a number points to consider.ImmutableSet
preserves the iteration order of the elements it's given. So if you have aTreeSet
and useImmutableSet.copyOf
to create an immutable copy, the copied elements will be ordered the same as in the original.ImmutableSortedSet
is the immutable equivalent ofTreeSet
and uses the natural ordering of elements or aComparator
just likeTreeSet
does.b) The fact that you can create a
List
that happens to be immutable without using Guava doesn't change anything. Guava's immutable collections are designed specifically with immutability in mind and they have various advantages because of that, including (but not limited to):ImmutableSet
, the caller knows that set can't change on them. Not so if it just returnsSet
.ImmutableSet.copyOf
etc. don't actually copy anything if the input is already an an immutable instance of the same type.