update method
- K key,
- V update(
- V value
- V ifAbsent()?,
override
Updates the value for the provided key
.
Returns the new value associated with the key.
If the key is present, invokes update with the current value and stores the new value in the map.
If the key is not present and ifAbsent
is provided, calls ifAbsent
and adds the key with the returned value to the map.
If the key is not present, ifAbsent
must be provided.
final planetsFromSun = <int, String>{1: 'Mercury', 2: 'unknown',
3: 'Earth'};
// Update value for known key value 2.
planetsFromSun.update(2, (value) => 'Venus');
print(planetsFromSun); // {1: Mercury, 2: Venus, 3: Earth}
final largestPlanets = <int, String>{1: 'Jupiter', 2: 'Saturn',
3: 'Neptune'};
// Key value 8 is missing from list, add it using [ifAbsent].
largestPlanets.update(8, (value) => 'New', ifAbsent: () => 'Mercury');
print(largestPlanets); // {1: Jupiter, 2: Saturn, 3: Neptune, 8: Mercury}
Implementation
V update(K key, V update(V value), {V Function()? ifAbsent}) {
var comparison = _splay(key);
if (comparison == 0) {
final originalModificationCount = _modificationCount;
final originalSplayCount = _splayCount;
var newValue = update(_root!.value);
if (originalModificationCount != _modificationCount) {
throw ConcurrentModificationError(this);
}
if (originalSplayCount != _splayCount) {
comparison = _splay(key);
// Can only fail to find the same key in a tree with the same
// modification count if a key has changed its comparison since
// it was added to the tree (which means the tree might no be
// well-ordered, so much can go wrong).
if (comparison != 0) throw ConcurrentModificationError(this);
}
_root!.value = newValue;
return newValue;
}
if (ifAbsent != null) {
final originalModificationCount = _modificationCount;
final originalSplayCount = _splayCount;
var newValue = ifAbsent();
if (originalModificationCount != _modificationCount) {
throw ConcurrentModificationError(this);
}
if (originalSplayCount != _splayCount) {
comparison = _splay(key);
// Can only happen if a key changed its comparison since being
// added to the tree.
if (comparison == 0) throw ConcurrentModificationError(this);
}
_addNewRoot(_SplayTreeMapNode(key, newValue), comparison);
return newValue;
}
throw ArgumentError.value(key, "key", "Key not in map.");
}