[英]Java HashSet duplicates comparison
I have a class Person
which contains String firstName, lastName
. 我有一个类Person
,其中包含String firstName, lastName
。 I want to insert instances of this class into a List
, but I don't want to insert duplicates. 我想将此类的实例插入List
,但我不想插入重复项。
How do I use a HashSet
such that it uses something like firstName+lastName
to figure out duplicates? 我如何使用HashSet
使得它使用firstName+lastName
类的东西来计算重复项?
You need an equals()
and a hashCode()
method in your Person
class. 你需要在Person
类中使用equals()
和hashCode()
方法。
equals()
is straightforward, and for hashCode()
the easiest solution is: equals()
很简单,而对于hashCode()
,最简单的解决方案是:
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. 虽然如果你的Person
对象是不可变的(因为它应该是,如果你把它放在一个HashSet中),你应该缓存这个值。
You need to make your .equals()
method return true
for two Person
s with the same first and last name. 你需要让你的.equals()
方法为具有相同名字和姓氏的两个Person
返回true
。 You need to also implement the .hashcode()
method to ensure that two equal object have the same hashcode. 您还需要实现.hashcode()
方法以确保两个相等的对象具有相同的哈希码。
Your question refers to using a List, and then mentions HashSet. 您的问题是指使用List,然后提到HashSet。 If preserving insertion order is important then a HashSet
is not what you want, you should use LinkedHashSet
. 如果保留插入顺序很重要,那么HashSet
不是你想要的,你应该使用LinkedHashSet
。
Important -> You need to implement equals AND hashcode 重要 - >您需要实现equals和hashcode
Always implement both. 始终实施两者。 And they must be consistent-> if 2 object are equals they must have the same hashcode. 并且它们必须是一致的 - >如果2个对象是等于它们必须具有相同的哈希码。
THIS IS VERY IMPORTANT. 这个非常重要。 READ AGAIN. 再读一遍。 :) :)
HashSets and HashMaps use hashcode and equals to compare elements. HashSets和HashMaps使用hashcode和equals来比较元素。 Diferent elements may have the same hashcode, but they are not equals 不同的元素可能具有相同的哈希码,但它们不等于
You should just use a Set
instead of a List
. 您应该只使用Set
而不是List
。 If you care about insertion order, use a LinkedHashSet
. 如果您关心插入顺序,请使用LinkedHashSet
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.