Collection类中的一些方法上有(optional operation)标识
例如:
add()方法
boolean java.util.Collection.add(E e)
Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as aresult of the call. (Returns false if this collection doesnot permit duplicates and already contains the specified element.)
Collections that support this operation may place limitations on whatelements may be added to this collection. In particular, somecollections will refuse to add null elements, and others willimpose restrictions on the type of elements that may be added.Collection classes should clearly specify in their documentation anyrestrictions on what elements may be added.
If a collection refuses to add a particular element for any reasonother than that it already contains the element, it must throwan exception (rather than returning false). This preservesthe invariant that a…
第一次看到不知道表达什么意思。
因为会想到,接口中的方法不都是要求必须实现的嘛。
查了下资料:
https://stackoverflow.com/questions/10572643/optional-methods-in-java-interface
得出结论
个人理解:当初Java的Collection接口设计者在设计的时候,因为要Collection的类有很多实现。
但是这些实现,并不是每一个都用得上这些方法。所以标注了optional operation。
问:既然不实现,为什么要继承Collection接口呢?
答案:因为如果要想完全地实现,每一个类继承”Collection“接口时,都用得上所有的方法。那么,需要设计很多接口。权衡之下,选择了optional operation标注。
具体例子:
Collections中的内部类UnmodifiableList。就是设计来作为:一个不可改变的List。它不需要add方法,但是接口还是继承了Collection。所以,它的add()方法的具体实现为,抛出一个标识没有实现该方法的异常
static class UnmodifiableList<E> extends UnmodifiableCollection<E>
implements List<E> {
private static final long serialVersionUID = -283967356065247728L;
final List<? extends E> list;
UnmodifiableList(List<? extends E> list) {
super(list);
this.list = list;
}
.....
//。所以,它的add()方法的具体实现为,如下
public boolean add(E e) {
throw new UnsupportedOperationException();
}