When using the DelayQueue of Java, should I implement equals() and hashCode() as well?

时间秒杀一切 提交于 2019-12-13 00:10:41

问题


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:


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.



来源:https://stackoverflow.com/questions/8446736/when-using-the-delayqueue-of-java-should-i-implement-equals-and-hashcode-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!