putIfAbsent 方法

V putIfAbsent(
  1. K key,
  2. V ifAbsent()
)
override

查找 key 的值,如果不存在则添加新的条目。

如果存在,则返回与 key 关联的值。否则调用 ifAbsent 获取新值,将 key 与该值关联,然后返回新值。

final diameters = <num, String>{1.0: 'Earth'};
final otherDiameters = <double, String>{0.383: 'Mercury', 0.949: 'Venus'};

for (final item in otherDiameters.entries) {
  diameters.putIfAbsent(item.key, () => item.value);
}
print(diameters); // {1.0: Earth, 0.383: Mercury, 0.949: Venus}

// If the key already exists, the current value is returned.
final result = diameters.putIfAbsent(0.383, () => 'Random');
print(result); // Mercury
print(diameters); // {1.0: Earth, 0.383: Mercury, 0.949: Venus}

调用 ifAbsent 时不得向映射中添加或删除键。

实现

V putIfAbsent(K key, V ifAbsent()) {
  int comp = _splay(key);
  if (comp == 0) {
    return _root!.value;
  }
  int modificationCount = _modificationCount;
  int splayCount = _splayCount;
  V value = ifAbsent();
  if (modificationCount != _modificationCount) {
    throw ConcurrentModificationError(this);
  }
  if (splayCount != _splayCount) {
    comp = _splay(key);
    // Key is still not there, otherwise _modificationCount would be changed.
    assert(comp != 0);
  }
  _addNewRoot(_SplayTreeMapNode(key, value), comp);
  return value;
}