retainAll 方法

void retainAll(
  1. Iterable<Object?> elements
)
override

从当前集合中移除所有不在 elements 中的元素。

检查 elements 中的每个元素,是否在当前集合中存在相等的元素(根据 this.contains 判断),如果存在,则保留该集合中的相等元素,并移除所有与 elements 中元素不相等的元素。

final characters = <String>{'A', 'B', 'C'};
characters.retainAll({'A', 'B', 'X'});
print(characters); // {A, B}

实现

void retainAll(Iterable<Object?> elements) {
  // Build a set with the same sense of equality as this set.
  SplayTreeSet<E> retainSet = SplayTreeSet<E>(_compare, _validKey);
  int modificationCount = _modificationCount;
  for (Object? object in elements) {
    if (modificationCount != _modificationCount) {
      // The iterator should not have side effects.
      throw ConcurrentModificationError(this);
    }
    // Equivalent to this.contains(object).
    if (_validKey(object) && _splay(object as E) == 0) {
      retainSet.add(_root!.key);
    }
  }
  // Take over the elements from the retained set, if it differs.
  if (retainSet._count != _count) {
    _root = retainSet._root;
    _count = retainSet._count;
    _modificationCount++;
  }
}