When in the java documentation for Set it says in the specification of a method Optional Operation
e.g. (emphasis by me)
add(E e)
Adds the specified element to this set if it is not already present (optional operation).
What does the optional mean here?
That if I use a JVM other than SUN/Oracle, this operation may not be provided by that implementation of Java?
That an interface method is specified as optional in the JavaDoc means that classes implementing this interface does not necessarily have to implement that method. Instead, they could for example, throw an exception.
More specifically, that an interface method is optional in the JavaDoc does not mean that it is implementation-specific behavior. Each concrete implementation of the class will specify whether it implements it or not. Looking at the HashMap class it includes the add operation and it does not specify it as optional. Thus, every implementation of the Java library will have to include an implementation of this method for their
HashMap
class. The same goes forTreeMap
etc.The reason why it might make sense for this operation to be declared as optional is because some sets may be conceptually immutable, such as those returned by Collections.unmodifiableSet
Set
is an interface. Classes implementing that interface do not necessarily need to provide an implementation for an optional operation.I think those optional operations go back to the general
Collection
interface where operations are made optional which do not make sense for some kinds of collections. E.g.add
is an operation that isn't really useful on some kind of read-only collection. It's spelt out explicitly in the Javadoc so it becomes part of what all collection classes offer but someone using it knows that, given some collection they do not know exactly, it could be that the method just throws anUnsupportedOperationException
.From the java.util.Collections documentation:
Note that many of the methods described there are not optional.
The Java Collections Framework is, arguably, not perfect; this may be one of the imperfections rearing its (tiny) head.