Java Collections – Why Use Optional Methods in Interfaces?

apidesignimmutabilityjava

During my first implementation extending the Java collection framework, I was quite surprised to see that the collection interface contains methods declared as optional. The implementer is expected to throw UnsupportedOperationExceptions if unsupported. This immediately struck me as a poor API design choice.

After reading much of Joshua Bloch's excellent "Effective Java" book, and later learning he may be responsible for these decisions, it didn't seem to gel with the principles espoused in the book. I would think declaring two interfaces: Collection, and MutableCollection which extends Collection with the "optional" methods would have led to much more maintainable client code.

There's an excellent summary of the issues here.

Was there a good reason why optional methods were chosen instead of the two interfaces implementation?

Best Answer

The FAQ provides the answer. In short, they saw a potential combinatorial explosion of needed interfaces with modifiable, unmodifiable view, delete-only, add-only, fixed-length, immutable (for threading), and so on for each possible set of implemented option methods.