Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Employee with same values is being added two times in HashSet

 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

I have created a Employee overriding equals and hashCode .

I am providing same values to the Employee Object , but please let me know why this is being added two times inside a HashSet (Even though they both are of same values
)

Please see the code ,



This is my client :

import java.util.HashSet;
import java.util.Iterator;



The output is :

The b vaue is true
The b2 vaue is true
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to the code, you are adding two different instances in to the HashSet, hence it behaves as expected. You are are not setting any values for the "emp3" instance?
 
Paul Lusk
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, As the previous reply mentions, you are not setting any values for emp3
# Employee emp3 = new Employee();
# emp1.setAge(25);
# emp1.setName("Ravi");
Suspect you were cutting and pasting and just forgot to change emp1 sets to emp3.
PL
 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey ,

I just want to see that as the Employees emp1 and emp2 are of same values , so the add must return false .

please correct me if i am wrong.
 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Paul for guiding , this works fine now .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic