*
The moose likes Java in General and the fly likes Employee with same values is being added two times in HashSet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Employee with same values is being added two times in HashSet" Watch "Employee with same values is being added two times in HashSet" New topic
Author

Employee with same values is being added two times in HashSet

Ravi Kiran Va
Ranch Hand

Joined: Apr 18, 2009
Posts: 2234

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


Save India From Corruption - Anna Hazare.
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3817

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?


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Paul Lusk
Ranch Hand

Joined: Aug 29, 2009
Posts: 34
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

Joined: Apr 18, 2009
Posts: 2234

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

Joined: Apr 18, 2009
Posts: 2234

Thanks Paul for guiding , this works fine now .
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Employee with same values is being added two times in HashSet
 
Similar Threads
Sorting arraylist on the basis of object
how comparator works?
Confusion about HashCode
equals() and hashCode()
A question About overriding equals and hashcode for an Object