Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashSet duplicates comparison

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?

like image 811
Verhogen Avatar asked Jul 18 '26 00:07

Verhogen


2 Answers

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.

like image 129
biziclop Avatar answered Jul 20 '26 15:07

biziclop


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.

like image 34
Matthew Gilliard Avatar answered Jul 20 '26 15:07

Matthew Gilliard