I have a class Person which contains String firstName, lastName. I want to insert instances of this class into a List, but I don’t want to insert duplicates.
How do I use a HashSet such that it uses something like firstName+lastName to figure out duplicates?
You need an
equals()and ahashCode()method in yourPersonclass.equals()is straightforward, and forhashCode()the easiest solution is:Although if your
Personobject is immutable (as it should be, if you’re putting it in a HashSet), you should cache this value.