equals method Null safety

  1. @override
bool equals(
  1. Map<K, V>? map1,
  2. Map<K, V>? map2
)
override

Compare two elements for being equal.

This should be a proper equality relation.

Implementation

@override
bool equals(Map<K, V>? map1, Map<K, V>? map2) {
  if (identical(map1, map2)) return true;
  if (map1 == null || map2 == null) return false;
  var length = map1.length;
  if (length != map2.length) return false;
  Map<_MapEntry, int> equalElementCounts = HashMap();
  for (var key in map1.keys) {
    var entry = _MapEntry(this, key, map1[key]);
    var count = equalElementCounts[entry] ?? 0;
    equalElementCounts[entry] = count + 1;
  }
  for (var key in map2.keys) {
    var entry = _MapEntry(this, key, map2[key]);
    var count = equalElementCounts[entry];
    if (count == null || count == 0) return false;
    equalElementCounts[entry] = count - 1;
  }
  return true;
}