我們來看官方文檔:
boolean retainAll(Collection<?> c)
Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.
翻譯過來,簡要意思就是:僅僅保留這個 set 中同時也在指定的 collection 中(即參數C)的元素。換句話來說,就是移除這個 set 中的所有的不包含在指定的 collection 中的元素。如果指定的 collection 也是一個 set,這個操作實際上就會修改調用這個方法的 set,使之剩下的元素為這兩個 set 的交集。
Specified by:
retainAll in interface Collection
Parameters:
c - collection containing elements to be retained in this set
Returns:
true if this set changed as a result of the call
Throws:
UnsupportedOperationException - if the retainAll operation is not supported by this set
ClassCastException - if the class of an element of this set is incompatible with the specified collection (optional)
NullPointerException - if this set contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null