将两个对象与哈希集进行比较的适当方法是什么?
我有一个人类,其中有一个名字和 HashSet 中的朋友列表。
我想重写此 Person 类的 equals
方法。以下是我到目前为止所写的内容。
但我对此不确定,因为我知道 HashSet 不一定必须按顺序,而且我还听说我必须重写 HashCode 方法。
我应该在下面的代码中进行哪些修改才能正确实现 equals 方法?
public boolean equals(Note target){
if(this.name==target.getName() && this.friends == target.getFriends()){
return true;
}
return false;
}
public HashSet<Person> getFriends(){
return this.friends;
}
编辑
//override hashCode()
public int hashCode() {
return name.hashCode() + friends.hashCode();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
==
运算符对于HashSet
和name
来说肯定是错误的。如果你想在java中比较对象,请使用equals方法。==
运算符比较 JVM 管理的内部对象 ID。HashSet
的equals
方法的约定位于AbstractSet.equals()
。您可能还想检查
null
,也许name
和fiends
可以为 null。关于
equals
和hashCode
已经写了很多。最好的方法是查看 JavaDoc 中的lava.lang.Object.equals()
。The
==
operator is definitely wrong for theHashSet
andname
. If you want to compare objects in java use the equals method. The==
operator compares the internal object IDs managed by the JVM. The contract forHashSet
'sequals
method is document inAbstractSet.equals()
.You may want to check for
null
's as well, maybename
andfiends
can be null.A lot has been writen regarding
equals
andhashCode
. The best way is to look into the JavaDoc forlava.lang.Object.equals()
.按照您目前的
equals(Note)
方法设置方式,它(几乎)永远不会返回true
。使用String
对象时,应始终使用equals(String)
,而不是==
。我将创建如下所示的
Note.equals(Note)
方法:您会注意到我上面提供的
equals(Note)
方法也不执行Friends.equals(target.getFriends())
。这是因为您正在比较包含的HashSet
,而不是HashSet
的内容。最后,如果您希望您的
Note
类正确散列,您还需要重写您的hashCode()
方法。您可以在hashCode()
方法.html” rel="nofollow">对象
文档。The way you currently have your
equals(Note)
method setup, it will (almost) never returntrue
. When working withString
objects you should always useequals(String)
, never==
.I would create my
Note.equals(Note)
method something like this:You will notice that the
equals(Note)
method I provided above also doesn't dofriends.equals(target.getFriends())
. This is because you are comparing the containingHashSet
, and not the contents of theHashSet
.Finally, if you want your
Note
class to hash properly, you will also need to override yourhashCode()
method. You can read more about this contract in the description of thehashCode()
method in theObject
documentation.