Stavo provando a eseguire il debug del mio codice che utilizza HashSet e cercando in SO, ho scoperto che avevo bisogno di sovrascrivere anche il metodo hashCode . La parte strana è, controllando l' API correlata , Non ho visto alcuna parte in esso menzionando il metodo hashCode . Citando la definizione del metodo add di HashSet come visto nell'API:
public boolean add(E e)
Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
Ora nella citazione sopra, non vedo da nessuna parte che menzioni il metodo hashCode . Non dovrebbe essere la frase corretta:
... if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)) AND if this set contains no element e2 such that (e==null ? e2==null : e.hashCode() == e2.hashCode()).
Ora se dici che: "Se o1.equals(o2) restituisce true, o1.hashCode() == o2.hashCode() DEVE anche valutare su true.", quindi vorrei fare tre domande:
-
Dove viene specificato questo fatto? (in generale o nell'API)
-
Anche se questo fatto è specificato da qualche parte, dove nell'API è specificato che
HashSetfa uso del metodohashCode? -
Se questo fatto è effettivamente corretto, perché il compilatore non impone l'override del metodo
hashCode, ogni volta che il metodoequalsviene sovrascritto?