Hash - Java HashMap hashCode equals - how to be consistent with multiple keys

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

   This question already has an answer here:
    * /questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java /questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java 11 answers

Answers

I think your question really goes a long way beyond plain implementation of hashCode - it s really about the design of when two IDs should be considered equal.

If you have multiple fields all of which are unique, you re actually in a tricky situation. Ignoring the MAC address part, there s nothing in the ID code itself to stop:

ID a = new ID("a", 0);
ID b = new ID("b", 0);
ID c = new ID("a", 1);

Now by your rules, those three IDs shouldn t all be able to co-exist - because they re all equal in one way or another. (a and b share the same name, and a and c share the same number.)

Additionally, it looks like the number and name are both effectively optional - that s likely to end up being painful, in my experience.

It may still make sense to keep your class as it is, but the rules around "No two entities can have the same name" and "No two entities can have the same number" aren t really the same as "no two entities can have the same ID", so you d have to enforce that separately.

It s entirely possible that you ll want to keep a HashMap<String, Entity> for "entities by name" and a HashMap<Integer, Entity> for "entities by number". I would then implement equals and hashCode in ID to check for complete equality - so that after looking up an ID by just one part of the ID, you can check that the ID you ve found is actually the right one.

Alternatively, change your identity scheme to only have a single part, so that you never need to worry about this. Even if you have a "secondary identifier" of some kind, it s worth deciding on one of them being your primary identifier which you normally use to look entities up, store them etc - and then you d just have a secondary mapping (whether that s in memory or in a database etc) between the primary and secondary identifiers. If all your "real" identifiers are optional, you may even want to have a surrogate identifier which is guaranteed to exist, and then all the mappings between that and the secondary identifiers can be optional. (They may even be mutable - you may be able to "discover" and record a social security number later against an existing entity, for example.)

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/30702269/java-hashmap-hashcode-equals-how-to-be-consistent-with-multiple-keys

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils