JaronTF
2/8/2019 - 1:51 PM

集合操作retainAll和removeAll

集合操作retainAll和removeAll

集合操作中有retainAll,也有removeAll,第一眼往往容易混淆,来看下JDK定义,

(1)retainAll

boolean retainAll(Collection<?> c)仅在列表中保留指定 collection 中所包含的元素(可选操作)。
换句话说,该方法从列表中移除未包含在指定 collection 中的所有元素。 
指定者:
接口 Collection<E> 中的 retainAll
参数:
c - 包含将保留在此列表中的元素的 collection 
返回:
如果此列表由于调用而发生更改,则返回 true 
抛出: 
UnsupportedOperationException - 如果列表不支持 retainAll 操作 
ClassCastException - 如果此列表的元素的类和指定的 collection 不兼容(可选) 
NullPointerException - 如果此列表包含一个 null 元素,并且指定的 collection 不允许 null 元素(可选),
或者指定的 collection 为 null
另请参见:
remove(Object), contains(Object)

(2)removeAll

boolean removeAll(Collection<?> c)从列表中移除指定 collection 中包含的其所有元素(可选操作)。 
指定者:
接口 Collection<E> 中的 removeAll
参数:
c - 包含从此列表中移除的元素的 collection 
返回:
如果此列表由于调用而发生更改,则返回 true 
抛出: 
UnsupportedOperationException - 如果列表不支持 removeAll 操作 
ClassCastException - 如果此列表中的元素的类和指定的 collection 不兼容(可选) 
NullPointerException - 如果此列表包含一个 null 元素,并且指定的 collection 不允许 null 元素(可选),
或者指定的 collection 为 null
另请参见:
remove(Object), contains(Object)

可见两者刚好相反,retainAll是用来剔除不在指定集合的元素,而removeAll是用来剔除在指定集合中的元素。 所以使用上retainAll可以用来取交集,而removeAll可以用来排除值。