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?
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 an UnsupportedOperationException
.
From the java.util.Collections documentation:
The "destructive" methods contained in this interface, that is, the
methods that modify the collection on which they operate, are
specified to throw UnsupportedOperationException if this collection
does not support the operation. If this is the case, these methods
may, but are not required to, throw an UnsupportedOperationException
if the invocation would have no effect on the collection. For example,
invoking the addAll(Collection) method on an unmodifiable collection
may, but is not required to, throw the exception if the collection to
be added is empty.
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.
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 for TreeMap
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