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 l开发者_运维百科ike 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 Person
s 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
.
You should just use a Set
instead of a List
. If you care about insertion order, use a LinkedHashSet
.
Important -> You need to implement equals AND hashcode
Always implement both. And they must be consistent-> if 2 object are equals they must have the same hashcode.
THIS IS VERY IMPORTANT. READ AGAIN. :)
HashSets and HashMaps use hashcode and equals to compare elements. Diferent elements may have the same hashcode, but they are not equals
精彩评论