“可选操作"是什么意思?例如 Set#add(E) 在 Javadoc 中的意思?

2022-01-17 00:00:00 set javadoc java

在 Set 它在方法规范中说 Optional Operation 例如(我强调)

When in the java documentation for Set it says in the specification of a method Optional Operation e.g. (emphasis by me)

添加(E e)
如果指定元素不存在,则将其添加到该集合中(可选操作).

这里的可选是什么意思?

What does the optional mean here?

如果我使用 SUN/Oracle 以外的 JVM,该操作可能不会由 Java 的实现提供?

That if I use a JVM other than SUN/Oracle, this operation may not be provided by that implementation of Java?

推荐答案

Set 是一个接口.实现该接口的类不一定需要为可选操作提供实现.

Set is an interface. Classes implementing that interface do not necessarily need to provide an implementation for an optional operation.

我认为那些可选操作会回到一般的 Collection 接口,其中操作是可选的,这对于 一些 种类的集合没有意义.例如.add 是一个对某种只读集合没有真正用处的操作.它在 Javadoc 中明确说明,因此它成为所有集合类提供的一部分,但使用它的人知道,鉴于 some 集合他们并不确切知道,可能是该方法只是抛出一个 UnsupportedOperationException.

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.

相关文章