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 a hashCode() method in your Person class.
equals() is straightforward, and for hashCode() the easiest solution is:
public int hashCode() {
return Arrays.hashCode( new Object[] { firstName, lastName } );
}
Although if your Person object is immutable (as it should be, if you're putting it in a HashSet), you should cache this value.
You need to make your .equals() method return true for two Persons with the same first and last name. You need to also implement the .hashcode() method to ensure that two equal object have the same hashcode.
Your question refers to using a List, and then mentions HashSet. If preserving insertion order is important then a HashSet is not what you want, you should use LinkedHashSet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With