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

130

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

Share:
130
dmjy
Author by

dmjy

Updated on January 03, 2023

Comments

  • dmjy
    dmjy over 1 year

    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()?

    • Philipos D.
      Philipos D. over 2 years
      Can you check what it extends / implements? Also when you try to Go To Definition in the IDE, where does it lead you?
    • Yunus Kocatas
      Yunus Kocatas over 2 years
      after clear() operation map will be empty {}
  • julemand101
    julemand101 over 2 years
    Yeah, not really helpful since this clue just points you to: github.com/dart-lang/sdk/blob/… which does not contain much implementation and not for clear(). ;)