How to Store unique objects to avoid the duplicates in java Set?
For example
Consider Employee object which (Employee Id, name, salary....)
list of employee of objects need to add in the Set. We need to restrict the Set for the duplicate elements which need to identify by the "Employee Id.
What are the best way's to do?
Similarly to @Dirk, you can also use HashCodeBuilder and EqualsBuilder from org.apache.commons.
It would look like this:
Set Stores unique object only
Eg:
add will return false when you will try to store the object which is already in the Set
If you are using an implementation of a
java.util.Set
, it should not allow duplicates as long as yourequals
andhashCode
methods are implemented properly. Not sure why you have hashmap and hashtable as tags on your question though. Maybe you should rephrase your question and add the code that gives you issues?Edit: considering your edit:
If you use a
Set
, your Employee should have the following methods: