Monday, September 27, 2010

How to Use an object as key for a hashmap in Java?

Using an object as key for HashMap then we need to make our class override the Object.equals() and Object.hashCode() methods.

I taken example as a ‘Person’ in a network, with my constructor looking something like the following:

public Person(String name) {
this.name = name;
}

now I use the following overrides:

public int hashCode()
{
return name.toString().hashCode();
}

public boolean equals(Object o) {
Person person = (Person)o;

if (person.name.equals(name))
{
return true;
}

return false;
}

and when i’m testing whether a particular key exists in the hashmap, I can create a new Person and check directly whether it currently exists as a key in the hashmap. Typically, if you didn’t implement this, then two person objects would have different references (even if they have the same name) and would not be equal.

No comments:

Post a Comment