Sobes.tech
Junior — Middle

Quali tipi di dati chiave sono ammessi per l'uso in una tabella hash?

sobes.tech AI

Risposta dell'AI

Nelle tabelle hash (ad esempio, in Dart, usato in Flutter), le chiavi possono essere oggetti di qualsiasi tipo, purché implementino correttamente i metodi hashCode e ==. Questo è necessario per calcolare correttamente il valore hash e confrontare le chiavi.

Di solito si usano tipi primitivi come stringhe (String), numeri (int), ma si possono usare anche classi personalizzate se questi metodi sono sovrascritti. Per esempio:

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] = 'Sviluppatore';
  print(map[p]); // Sviluppatore
}

Pertanto, le chiavi devono essere immutabili e avere metodi hashCode e == correttamente implementati.