Junior — Middle
Explain the working principle of a hash function and its usage.
sobes.tech AI
Answer from AI
A hash function is a function that takes input data of arbitrary size and returns a fixed-size hash (usually a number or a string). The main property of a hash function is that the same input always produces the same output, and a small change in the input significantly alters the result.
In Flutter (and programming in general), hash functions are often used for quick comparison of objects, for example, when stored in collections like Set or Map. Instead of comparing all fields of an object, their hash codes are compared.
Example of usage in Dart:
class Person {
final String name;
final int age;
Person(this.name, this.age);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Person && name == other.name && age == other.age;
@override
int get hashCode => name.hashCode ^ age.hashCode;
}
Here, hashCode combines the hashes of the fields to produce a unique hash for the object. This speeds up operations with collections and helps quickly find objects.