David Sowerby opened issue #205: Explanation for ordering of content at David Sowerby / takkan

David Sowerby
2023-10-24T12:55:33Z

In Dart, the {key:value} syntax is shorthand for creating a Map literal. The underlying type of the Map will be LinkedHashMap, which preserves insertion order.

So in your example:

var map = {'a':1,'B':2};

map is a LinkedHashMap and is ordered. The keys and values will iterate in the order they were defined.

A few key points:

Map literals use LinkedHashMap by default to preserve ordering.

The Map class itself does not preserve order. If created like:

var map = Map();

it will be a HashMap which does not preserve insertion order.

LinkedHashMap preserves insertion order while still providing O(1) lookup like HashMap.

If order does not matter, HashMap is more efficient than LinkedHashMap.

So in summary, yes the Map literal syntax creates an ordered LinkedHashMap by default in Dart. This provides both efficient lookup and ordered iteration.