I have an ID class. It refers to identification for a unique person. There are two forms of ID. Username and user number. If either username matches or user number matches, the ID's refer to the same person. I want to use the ID class as a key in a hashmap for looking up persons. I overrode the equals method to make it clear that if two ID's are equal, that means they refer to the same person. I am under the presumption that I need to override the hashCode() method because I want a hashmap of < key: ID, value: Person >. But I don't know how. How do I make the ID class an acceptable key for my HashMap?
public final class ID {
// These are all unique values. No 2 people can have the same username or id value.
final String username_;
final long idNumber_;
public ID(String username, Byte[] MACaddress, long idNumber) {
username_ = username;
idNumber_ = idNumber;
}
/**
* Checks to see if the values match.
* If either username or idNumber matches, then both ID's refer to the same person.
*/
public boolean equals(Object o) {
if (!(o instanceof ID)) {
return false;
}
ID other = (ID) o;
if (this.username_ != null && other.username_ != null) {
if (this.username_.equals(other.username_)) {
return true;
}
}
if (this.idNumber_ > 0 && other.idNumber_ > 0) {
if(this.idNumber_ == other.idNumber_) {
return true;
}
}
return false;
}
}
Followup: What if I wanted to add a third field for unique social security number? How would that change my person lookup hashmap and the ID class?
Note that the Wikipedia page for hashCode says:
The general contract for overridden implementations of this method is that they behave in a way consistent with the same object's equals() method: that a given object must consistently report the same hash value (unless it is changed so that the new version is no longer considered "equal" to the old), and that two objects which equals() says are equal must report the same hash value.
Update
Best solution thus far: Make a separate HashMap for each immutable unique identifier and then wrap all the HashMaps in a wrapper object.