Solved: Where is the definition of `map.clear()`?

Question

Asked by dmjy on January 13, 2022 (source).

I'm checking the implementation of Map. (map.dart in dart:collection)

I find void clear(); in abstract class Map<K, V>. clear() doesn't have any implementation and class Map doesn't extend/implement any other classes. But I can still call clear().

example

Map<int, int> m = <int, int>{1: 1, 2: 2};
m.clear();

Where can I find the implementation of clear()?

Answer

Question answered by julemand101 (source).

My answer is based on the assumption that you want the implementation used when Dart is running natively and not on the web.

The default Map in Dart is a LinkedHashMap. There are several layers before getting the implementation of clear() but I expect this is the one you are looking for:

  void clear() {
    if (!isEmpty) {
      _index = _uninitializedIndex;
      _hashMask = _HashBase._UNINITIALIZED_HASH_MASK;
      _data = _uninitializedData;
      _usedData = 0;
      _deletedKeys = 0;
    }
  }

https://github.com/dart-lang/sdk/blob/2.15.1/sdk/lib/_internal/vm/lib/compact_hash.dart#L333-L341

DART DICTIONARY FLUTTER
SHARE: