Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to use Hashmap's containsKey method for Objects

801487Dec 12 2008 — edited Dec 12 2008
Hi Friends,
I have a custom class Person and I would like to store only unique Person objects into a hashmap. But I am confused on how to compare objects using the hashmap's containKey method.

So,I am trying something like this:
HashMap<Person,Integer> persons = new HashMap<Person,Integer>();
Person p = new Person("tester"); //person constructor with name

//add person object only if it does not exists
if(persons.containsKey(p)){ // this is what i am confused with
 //do something
}
else{
persons.add(p,1);
}
But I am connfused how to compare objects of a particular class??? Do I need to add "equals" or some other method to the Person class or is there any other way???

Any help would be appreciated
Thanks
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 9 2009
Added on Dec 12 2008
7 comments
1,082 views