PDA

View Full Version : [Java] Hasmap e containsKey


guylmaster
09-03-2012, 13:10
Salve a tutti,
se ho un hasmap dove la chiave è una mia classe Cella che si può contraddistingue univocamente da attibruti ovvero Latitudine e Longitudine che sono due double.

Come faccio a dire che il containsKey di questa hasmap debba controllare appunto questi due valori di longitudine e latitudine? Perché di base sugli oggetti sembra che agisca solo sul riferimento, filava tutto liscio solo se lavoravo con chiavi di tipo primitivo.

Vi ringrazio in anticipo,
guylmaster

wingman87
09-03-2012, 13:49
In Cella devi definire l'override dei metodi hashCode ed equals in modo appropriato.

Fonte:
Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the contains(Object key) method says: "returns true if and only if this map contain a mapping for a key k such that (key==null ? k==null : key.equals(k))." This specification should not be construed to imply that invoking Map.containsKey with a non-null argument key will cause key.equals(k) to be invoked for any key k. Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two keys. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Map.html

banryu79
09-03-2012, 14:01
Se usi classi custom come chiavi delle Collection devi fornire una adeguata implementazione dei metodi equals e hashCode.
Nel tuo caso, se l'identità di una istanza di Cella è univocamente definita dal valore di latitutdine e longitudine allora dovrai implementare equals e hashCode tenendo conto di questo, dunque dovrai dire che:

1) una Cella A equals un'altra Cella B se e solo se i valori latitudine e longitudine di A e di B sono tra loro uguali.

2) l'hashCode di una Cella è calcolato in base al valore di latitudine e longitune di quella Cella.

3) per quanto detto in 1 e 2 segue che se una Cella A equals un'altra Cella B allora l'hashCode di A deve essere uguale all'hashCode di B.

In Java per dire queste tre cose devi implementare adeguatamente i metodi equals & hashCode; se non lo fai le istanze della tua classe Cella ereditano (ovviamente) i comportamenti definiti in Object.

P.S.: dato che longitudine e latitudine sono dei double, nell'implementare equals e hashCode ti tornerà utile il metodo statico Double.doubleToLongBits (hashCode deve restituire un long). Inoltre puoi sbirciare i sorgenti di Double per vedere come implementa i suoi equals e hashCode, tu dovresti fare una cosa simile, solo che hai due double invece che uno ;)