Junior — Middle
What types of key data are allowed for use in a hash table?
sobes.tech AI
Answer from AI
In hash tables (for example, in Dart used in Flutter), keys can be objects of any type, provided they correctly implement the hashCode and == methods. This is necessary for proper hash value computation and key comparison.
Most commonly, primitive types such as strings (String) and numbers (int) are used, but custom classes can also be used if these methods are overridden. For example:
class Person {
final String name;
final int id;
Person(this.name, this.id);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Person && runtimeType == other.runtimeType && id == other.id;
@override
int get hashCode => id.hashCode;
}
void main() {
var map = <Person, String>{};
var p = Person('Alice', 1);
map[p] = 'Developer';
print(map[p]); // Developer
}
Thus, keys should be immutable and have correctly implemented hashCode and == methods.