HashMap<K, V> constructor Null safety

HashMap<K, V>(
  1. {bool equals(
    1. K,
    2. K
    ),
  2. int hashCode(
    1. K
    ),
  3. bool isValidKey(
    1. dynamic
    )}
)

Creates an unordered hash-table based Map.

The created map is not ordered in any way. When iterating the keys or values, the iteration order is unspecified except that it will stay the same as long as the map isn't changed.

If equals is provided, it is used to compare the keys in the table with new keys. If equals is omitted, the key's own Object.== is used instead.

Similar, if hashCode is provided, it is used to produce a hash value for keys in order to place them in the hash table. If it is omitted, the key's own Object.hashCode is used.

If using methods like operator [], remove and containsKey together with a custom equality and hashcode, an extra isValidKey function can be supplied. This function is called before calling equals or hashCode with an argument that may not be a K instance, and if the call returns false, the key is assumed to not be in the set. The isValidKey function defaults to just testing if the object is a K instance.

Example:

new HashMap<int,int>(equals: (int a, int b) => (b - a) % 5 == 0,
                     hashCode: (int e) => e % 5)

This example map does not need an isValidKey function to be passed. The default function accepts only int values, which can safely be passed to both the equals and hashCode functions.

If neither equals, hashCode, nor isValidKey is provided, the default isValidKey instead accepts all keys. The default equality and hashcode operations are assumed to work on all objects.

Likewise, if equals is identical, hashCode is identityHashCode and isValidKey is omitted, the resulting map is identity based, and the isValidKey defaults to accepting all keys. Such a map can be created directly using HashMap.identity.

The used equals and hashCode method should always be consistent, so that if equals(a, b) then hashCode(a) == hashCode(b). The hash of an object, or what it compares equal to, should not change while the object is a key in the map. If it does change, the result is unpredictable.

If you supply one of equals and hashCode, you should generally also to supply the other.

Implementation

external factory HashMap(
    {bool Function(K, K)? equals,
    int Function(K)? hashCode,
    bool Function(dynamic)? isValidKey});