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?
If you are using an implementation of a
java.util.Set, it should not allow duplicates as long as yourequalsandhashCodemethods 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: