hashAllUnordered static method

  1. @Since("2.14")
int hashAllUnordered(
  1. Iterable<Object?> objects
)

Creates a combined hash code for a collection of objects.

The hash code is computed for elements in objects, even if they are null, by numerically combining the Object.hashCode of each element in an order independent way.

The result of hashAllUnordered({o}) is not o.hashCode.

Example:

bool setEquals<T>(Set<T> set1, Set<T> set2) {
  var hashCode1 = Object.hashAllUnordered(set1);
  var hashCode2 = Object.hashAllUnordered(set2);
  if (hashCode1 != hashCode2) return false;
  // Compare elements ...
}

The computed value will be consistent when the function is called again with objects that have the same hash codes during an execution of a single program, even if the objects are not necessarily in the same order,

The hash value generated by this function is not guaranteed to be stable over different runs of the same program. The exact algorithm used may differ between different platforms, or between different versions of the platform libraries, and it may depend on values that change on each program execution.

Implementation

@Since("2.14")
static int hashAllUnordered(Iterable<Object?> objects) {
  int sum = 0;
  int count = 0;
  const int mask = 0x3FFFFFFF;
  for (var object in objects) {
    int objectHash = SystemHash.smear(object.hashCode);
    sum = (sum + objectHash) & mask;
    count += 1;
  }
  return SystemHash.hash2(sum, count, 0);
}