This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B Self Test Pg 617, Q12- HashSet doubt

 
Siri Naray
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When i run this program I see that all five Person Objects are added to HashSet. HashSet doesnot add duplicates. Then why is "Hans" and "Jane" added twice to HashSet??

public static void main(String[] args) {
Group g = new Group();
g.add(new Person("Hans"));
g.add(new Person("Lotte"));
g.add(new Person("Jane"));
g.add(new Person("Hans"));
g.add(new Person("Jane"));
System.out.println("Total: " +g.size());
}}
public boolean add(Person o)
{
System.out.println("Adding: "+ o);
return super.add(o);
}

}
class Person{
private final String name;
public Person(String name){ this.name = name;}
public String toString(){ return name;}

}

Output:
Adding: Hans
Adding: Lotte
Adding: Jane
Adding: Hans
Adding: Jane
Total: 5


Thank you
sirisha
 
sharad sinha
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

When i run this program I see that all five Person Objects are added to HashSet. HashSet doesnot add duplicates. Then why is "Hans" and "Jane" added twice to HashSet??


What makes you to think that the two Person Objects should be same only because they have similar names ???
Did you do anything in your Person class to tell the JVM how to test for equality?
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You must implement (override) hashCode() method in PersonClass.
HashSet uses hashcodes to store/search objects. hashCode must return the same value for identical objects. In your Person class hashCode() from Object is used, which by default returns different values for each individual object, and therefore HashSet treats both "jane" persons as different.
Try simple hashCode below , it should work:

[ August 26, 2008: Message edited by: Ireneusz Kordal ]
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Sirishaaaaa Ghatty",
did you check Bear's message from this thread ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic