-
add
boolean add(E e)
Ensures that this collection contains the specified element (optional operation)<可选操作>. Returnstrue
if this collection changed as a result of the call. (Returnsfalse
if this collection does not permit<允许> duplicates<重复> and already contains the specified element.)Collections that support this operation may place limitations on what elements may be added to this collection. In particular, some collections will refuse to add
null
elements, and others will impose restrictions on the type of elements that may be added. Collection classes should clearly specify in their documentation any restrictions on what elements may be added.If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning
false
). This preserves the invariant that a collection always contains the specified element after this call returns.-
Parameters:
-
e
- element whose presence in this collection is to be ensured
Returns:
-
true
if this collection changed as a result of the call
Throws:
-
UnsupportedOperationException
- if theadd
operation is not supported by this collection -
ClassCastException
- if the class of the specified element prevents it from being added to this collection -
NullPointerException
- if the specified element is null and this collection does not permit null elements -
IllegalArgumentException
- if some property of the element prevents it from being added to this collection -
IllegalStateException
- if the element cannot be added at this time due to insertion restrictions
-
JDK里面Collection接口的add方法和remove方法的实现如下(Java安装目录下的src文件):
public boolean add(E e) {
throw new UnsupportedOperationException();
}
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
public boolean addAll(Collection<? extends E> coll) {
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
public void clear() {
throw new UnsupportedOperationException();
}