使用Java的DelayQueue时,是否也应该实现equals()和hashCode()?
我当前正在处理一个使用 DelayQueue
的类。我注意到,由于 DelayQueue
中的对象实现了 Delayed
接口,因此所述对象还需要实现 compareTo()
方法,这已经完成了。
这是否隐含意味着我也应该考虑实现 equals()
方法和 hashCode()
方法?
I'm currently dealing with a class that's using a DelayQueue
. I've noticed that since the objects in the DelayQueue
implement the Delayed
interface, the said objects need to implement a compareTo()
method as well, which has already been done.
Does this implicitly mean that I also should consider implementing an equals()
method and a hashCode()
method as well?
The reason why I'm asking is because I stumbled upon this advice when searching through the project via FindBugs, and I'm trying to figure out whether it's needed or not for this particular case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为一个好的实践,是的,因为
equals
、hashCode
和compareTo
具有接近的含义。它们可以被视为同一事物的不同方面。如果您的对象在其他地方使用而没有一起实现它们,您可能会遇到不可预测的行为。例如,您已将对象传递给使用二分搜索算法的第三方库,它使用
compareTo
。几个月后,该库的新版本更改为基于哈希的数据结构以提高性能,该结构依赖于equals
和hashCode
。从他们的角度来看,这并不是重大变化。在本例中,不会,因为
DelayQueue
不使用它们。As a good practice, yes, since
equals
,hashCode
andcompareTo
has close meanings. They can be seen as different aspects of the same thing. If you object is used someplace else without implementing them together, you may meet unpredictable behavior.For example, you've passed your object to a 3rd party library which use binary search algorithm, it uses
compareTo
. Several months later, the new version of the library change to hashed based data structure to improve performance, which relay onequals
andhashCode
. From their point of view, it's not breaking change。As in this case, no, since
DelayQueue
doesn't use the them.