When using the DelayQueue of Java, should I implem

2019-07-25 18:49发布

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.

1条回答
唯我独甜
2楼-- · 2019-07-25 18:57

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.

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。

As in this case, no, since DelayQueue doesn't use the them.

查看更多
登录 后发表回答