Wrappers for Java Collections that let you expose only read-only interfaces where you need to.
Java Collections API is flawed in a way that every collection interface has
mutator methods like add()
, remove()
or put()
. This presents the following
implications:
Mutable collections and read-only collections are two completely different sets of abstractions. Mutable collections are data structures. Read-only collections are mathematical objects:
In math texts, when we give a mathematical object a name, like "let set A be {x | x > 3 and x < 9} united with {y | y > -2 and y <1}", we don't change contents of a math object referred by that name. For instance, we don't add elements saying "let set A be the same set A but with one more element k". That is similar to the concept of immutability in programming.
Lack of mutators removes unnecessary complexity that would be here if we were to
represent math objects with java.util.Collection
implementations.
When you implement a Collection descendant interface (List
, Set
) or Map
,
you have to provide an implementation for methods like add()
and put()
. If
your collection is not supposed to be mutated (but rather populated at the
construction time, as for example Guava Collections), then you don't need those
methods. But you have to provide at least some implementation, so you stub those
methods with something like:
public class Polygon implements List<Point2D> {
//...
@Deprecated
@Override
public void add(Point2D point) {
throw new UnsupportedOperationException();
}
}
And those methods will still show up in the completion dialog in your IDE and in the documentation.