Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "optional operation" mean in Javadoc of for example Set#add(E)?

Tags:

java

set

javadoc

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?

like image 367
Cratylus Avatar asked Dec 04 '11 13:12

Cratylus


People also ask

What does optional operation mean?

It means that an implementor can provide the operation if appropriate, but can also not provide the operation and still be compliant with the intention of the interface.

What is an optional operation in Java?

Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.

CAN interface have optional methods?

The "third statement" says that abstract interface methods must always be implemented and this remains true in Java 8+. However, as in the Java Collections Framework, it is possible to describe some abstract interface methods as "optional" in the contract.


1 Answers

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.

like image 65
Joey Avatar answered Dec 07 '22 04:12

Joey