Extending ImmutableCollection

guava, java

Solution

Many of the operations in the Collection interface are considered optional. You could write your own implementation on that and throw the UnsupportedOperationException for any action your implementation does not support. This would be a way to get around having to extend ImmutableCollection.

Subclassing ImmutableCollection is probably not an option, as its documentation states the following:

An immutable collection. Does not permit null elements.

Note: Although this class is not final, it cannot be subclassed outside of this package as it has no public or protected constructors. Thus, instances of this type are guaranteed to be immutable.

Problem

I'd like to build a data model that conveys an iterator and a size, basically a read-only way of iterating a result set's elements. I figured extending ImmutableCollection and implementing size() and iterator() was the best course of action, since this type adequately communicates my intent. Unfortunately, ImmutableCollection has a package-private isPartialView. My question: Why is isPartialView package-private, should it remain so, and if so, what is the best way to model my read-only collection? Should I be creating a custom type with only the size() and iterator() methods (a SizedIterable)? Are there other suggestions for this use case?

Original source