ImmutableList does not expand the list?

When I dig up the gs-collection source for ImmutableList , it does not extend java.util.List . However, the javadoc class mentioned that the implementation of All ImmutableList should implement java.util.List .

Why do I need to ask the implementation to implement java.util.List , and not ImmutableList for the java.util.List extension?

+5
source share
1 answer

Why is not ImmutableList expanding List ?

ImmutableCollection does not extend java.util.Collection (and ImmutableList does not extend java.util.List ), because Collection has mutating methods like add() and remove() . If immutable collections had these methods, they always had to throw an UnsupportedOperationException . For users of immutable collections, it would be weird to see add() and remove() in autocomplete as called methods.

Why does Javadoc impose a contract that all ImmutableList implementations also implement List ?

It comes down to equality. ImmutableList should be equal to a List if both lists have the same content in the same order. List.equals() imposes a Javadoc contract that states:

Returns true if and only if the specified object is also a list, as lists are the same size, and all the corresponding pairs of elements in two lists are equal.

What does it mean that "the specified object is also a list?" We can see in AbstractList.equals() that this means instanceof List .

 public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof List)) return false; ... } 

Thus, all ImmutableList implementations must also implement List for equals() to work in a symmetrical way. Immutable collection factories already hide implementation details, such as the fact that an immutable one-element list is implemented by an ImmutableSingletonList . It also completes the hiding of the List interface.

ImmutableList class diagram

Interop

The advantage of this design is that an ImmutableList can be added to the List , which is important for interacting with existing APIs.

 // Library method - cannot refactor the parameter type public void printAll(List<?> list) { for (Object each : list) { System.out.println(each); } } ImmutableList<Integer> immutableList = Lists.immutable.with(1, 2, 3); List<Integer> castList = immutableList.castToList(); printAll(castList); // also works printAll((List<?>) immutableList); // throws UnsupportedOperationException castList.add(4); 

Note: I am a developer of the GS Collection .

+11
source

All Articles