JavaMiscellaneous: Optional Collection methods

Optional Collection methods

java.util.Collection allows its modification to be optional, i.e. they may throw UnsupportedOperation (or other expections if the passed-in data is invalid). However, it is reasonable to assume that the behaviour of these methods is somehow coupled and the Collection may not react totally arbitrarily in what it accepts. I used more common sense than sticking to the exact words of the documentation.

I have avoided the use of "should" etc. in the following, but these are nevertheless just my opinions.

May UnsupportedOperationException be thrown depending on circumstances (and not always or never) at all? Why is UnsupportedOperationException documented per method, not per "logical" operation?


add() and addAll() are supported both or none. addAll can be implemented from the outside on top of add, and add on addAll, so why should these methods react differently? Possibly only because some items have to be added all at once, and not independent from each other.

For a List, add(item) is equivalent to add(size(), item). (Even if the list does not allow insertion at arbitrary places, but allows add(item), it has to support add(size(), item). Is this allowed at all?.

The same goes for addAll(index, collection).

For a List, if the Iterator supports add(), the List does as well, but not necessarily the other way around.


If the iterator supports remove(), the Collection supports remove() as well. The Collection's remove() method could be implemented on top of the Iterator.

If the Collection supports remove(), it also supports removeAll() and retainAll(), and vice versa. If it allows to remove any item, it also supports clear(). If there are (or might be) some items that cannot be removed, clear() may not be supported.

If the Collection supports removal, its Iterator need not necessarily do it as well. There are implementations where removal of an item would destroy the iteration order, so Iterator's remove could only be implemented by copying all data (undesirable).

For a List, if remove(item) is supported, remove(indexOf(item)) is supported as well, and vice versa.

Replacing (List)

If the Iterator supports set(), the List does as well, but not vice versa.

Supporting set() does not imply supporting add() and remove() (The List may be fixed size).

Supporting add() and remove() implies supporting set(), since set() can be implemented on top of them.

Classification of Collection types

The following blocks of methods can be supported independently from each other. (=> means "implies").

Classification of List types

It is actually hard to imagine why the iterator shouldn't support any of its modification methods if the List does.

(C) 2001-2009 Christian Kaufhold (