delete method
void
delete(
- K key
Removes the entry with the given key.
Uses a swap-with-last strategy to maintain O(1) deletion:
- Swaps the element to delete with the last element
- Updates the map for the swapped element
- Removes the last element from the list
If the key doesn't exist, this operation is a no-op.
Time complexity: O(1)
Example:
final map = FastMap<String, int>();
map.set('a', 1);
map.set('b', 2);
map.delete('a'); // Swaps 'a' with 'b', then removes last
Implementation
void delete(K key) {
if (!_keyToIndex.containsKey(key)) return;
final indexToDelete = _keyToIndex[key]!;
final lastIndex = _values.length - 1;
if (indexToDelete != lastIndex) {
// Swap with last element
_values[indexToDelete] = _values[lastIndex];
// Update the map for the swapped element
final swappedKey = _keyToIndex.entries
.firstWhere((entry) => entry.value == lastIndex)
.key;
_keyToIndex[swappedKey] = indexToDelete;
}
// Remove the last element and the key
_values.removeLast();
_keyToIndex.remove(key);
}