使用Java的DelayQueue时,我是否也应该实现equals()和hashCode()? [英] When using the DelayQueue of Java, should I implement equals() and hashCode() as well?
问题描述
我目前正在处理使用DelayQueue
的类.我注意到,由于DelayQueue
中的对象实现了Delayed
接口,因此上述对象也需要实现compareTo()
方法,该方法已经完成.
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.
这是否暗示我也应该考虑实现equals()
方法和hashCode()
方法?
Does this implicitly mean that I also should consider implementing an equals()
method and a hashCode()
method as well?
我问的原因是因为我偶然发现了 此建议 通过 FindBugs 搜索项目时,我正在尝试确定是否需要是否适合这种情况.
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.
推荐答案
好的做法是,因为equals
,hashCode
和compareTo
具有紧密的含义.可以将它们视为同一事物的不同方面.如果您在其他地方使用对象而没有一起实施,则可能会遇到无法预料的行为.
As a good practice, yes, since equals
, hashCode
and compareTo
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.
例如,您已将对象传递给使用二进制搜索算法的第三方库,该库使用compareTo
.几个月后,该库的新版本更改为基于散列的数据结构以提高性能,该结构以equals
和hashCode
为基础.从他们的角度来看,这并没有改变.
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 on equals
and hashCode
. From their point of view, it's not breaking change。
在这种情况下,不可以,因为DelayQueue
不使用它们.
As in this case, no, since DelayQueue
doesn't use the them.
这篇关于使用Java的DelayQueue时,我是否也应该实现equals()和hashCode()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!