• Post Reply Bookmark Topic Watch Topic
  • New Topic

Hash Set  RSS feed

 
Pankaj Shet
Ranch Hand
Posts: 320
Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I have one question regarding Hash set.

Suppose if i have a class Employee.

class Employee{

String fstName;
String lstName;

public Employee(String fstName,String lstName){
this.fstName= fstName;
this.lstName= lstName;
}

... getter setter methods for both the properties..

}


Now I have a hashset where i add the employee objects like this:

Set hs = new HashSet();

hs.add(new Employee("Pankaj", "Shet"));
hs.add(new Employee("Pankaj", "Shet"));

Now above code will add both the objects as the are distinct objects. right?

How to design the above scenerio such that I don't want new Employee("Pankaj", "Shet") to be added more than once.

or when added to hashSet, I don't want new Employee object to contain same first name and last name again.?

Regards,
-Pankaj.



 
Paweł Baczyński
Bartender
Posts: 2077
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to override Object#equals and Object#hashCode.
Tell us if you have any question about it.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll have to implement equals() and hashCode() methods in your class Employee; those methods are what determine if two Employee methods are equal or different.

See the API documentation of equals() and hashCode() in class java.lang.Object for information on the requirements for these methods.
 
Pankaj Shet
Ranch Hand
Posts: 320
Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks both of you for your prompt reply.
Got it..
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!