Use custom object as key
suggest changeBefore using your own object as a key you must override the hashCode() and equals() methods of your object.
In simple case you would have something like:
class MyKey {
private String name;
MyKey(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof MyKey) {
return this.name.equals(((MyKey)obj).name);
}
return false;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
}
hashCode will decide which hash bucket the key belongs to and equals will decide which object inside that hash bucket.
Without these methods, the reference of your object will be used for the comparison above, which will not work unless you use the same object reference every time.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents