Java HashSet 重复项比较
我有一个类 Person
,其中包含 String firstName, lastName
。我想将此类的实例插入 List
中,但我不想插入重复项。
如何使用 HashSet
使其使用诸如 firstName+lastName
之类的内容来找出重复项?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的
Person
类中需要一个equals()
和一个hashCode()
方法。equals()
很简单,对于hashCode()
最简单的解决方案是:尽管如果您的
Person
对象是不可变的(因为它应该是,如果你将它放入 HashSet 中),你应该缓存这个值。You need an
equals()
and ahashCode()
method in yourPerson
class.equals()
is straightforward, and forhashCode()
the easiest solution is:Although if your
Person
object is immutable (as it should be, if you're putting it in a HashSet), you should cache this value.您需要使您的
.equals()
方法为两个具有相同名字和姓氏的Person
返回true
。您还需要实现 .hashcode() 方法以确保两个相等的对象具有相同的哈希码。你的问题涉及到使用List,然后提到HashSet。如果保留插入顺序很重要,那么
HashSet
不是您想要的,您应该使用LinkedHashSet
。You need to make your
.equals()
method returntrue
for twoPerson
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 useLinkedHashSet
.您应该只使用
Set
而不是List
。如果您关心插入顺序,请使用LinkedHashSet
。You should just use a
Set
instead of aList
. If you care about insertion order, use aLinkedHashSet
.重要->您需要实现 equals AND hashcode
始终同时实现两者。并且它们必须是一致的->如果两个对象相等,它们必须具有相同的哈希码。
这非常重要。
再读一遍。 :)
HashSet 和 HashMap 使用 hashcode 和 equals 来比较元素。不同的元素可能有相同的hashcode,但它们不相等
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