What are the differences between the different Map implementations in Dart?

前端 未结 3 1922
暗喜
暗喜 2020-12-29 02:46

Dart has a Map type, with implementations like HashMap, LinkedHashMap, and SplayTreeMap. What\'s the difference between those different Map implementations?

3条回答
  •  臣服心动
    2020-12-29 03:08

    Key points to note about Dart Map

    A Dart Map is a collection of key-value pairs. It maps each key to exactly one value. We can iterate over a Map.

    There are three types of map, depending in the order of iteration:

    • HashMap is unordered. The key-value pair coming later could be ordered first.
    • LinkedHashMap has predictable iteration order by the insertion order. The key-value pair coming later will be ordered later.
    • SplayTreeMap iterates the keys in sorted order. It is a self-balancing binary tree, frequently accessed elements will be moved more closely to the root of the tree.

    By default, creating an instance using Map constructor (Map(), Map.from(), Map.of()) will return a LinkedHashMap.

    wherever we use Map, you can think about LinkedHashMap, and you can also replace Map with LinkedHashMap.

    Create a new Map in Dart/Flutter

    Using new keyword, we can create a new Map.

    Don’t forget to import dart:collection library before using these syntax containing HashMap, LinkedHashMap, SplayTreeMap, also other code in the rest of this answer

    import 'dart:collection';
    
    main() {
      HashMap hashMap = new HashMap();
      LinkedHashMap linkedHashMap = new LinkedHashMap();
      SplayTreeMap treeMap = new SplayTreeMap();
    }
    

    With recent Dart version, we don’t need to use new keyword anymore. For example, HashMap map = HashMap() is accepted.

    We can create a new LinkedHashMap using Map constructor like this.

    Map map = Map();
    if (map is LinkedHashMap) {
      print("This is a LinkedHashMap.");
    }
    
    // Result: This is a LinkedHashMap.
    

    In the code above, we specify the type of key-value pairs: . You can also declare a Map, LinkedHashMap, SplayTreeMap without setting the type for their keys and values. What does it mean? It will not constrain us to add a pair into the Map.

    These Maps now accept other types: ,

    Map map = Map();
    HashMap map1 = HashMap();
    LinkedHashMap map2 = LinkedHashMap();
    SplayTreeMap map3 = SplayTreeMap();
    

    More : A complete reference

提交回复
热议问题