使用Java的DelayQueue时,是否也应该实现equals()和hashCode()?

发布于 2024-12-20 13:10:54 字数 527 浏览 3 评论 0原文

我当前正在处理一个使用 DelayQueue 的类。我注意到,由于 DelayQueue 中的对象实现了 Delayed 接口,因此所述对象还需要实现 compareTo() 方法,这已经完成了。

这是否隐含意味着我也应该考虑实现 equals() 方法和 hashCode() 方法?

我问是因为我偶然发现这个通过 FindBugs 搜索项目时的建议,我正在尝试弄清楚确定这种特殊情况是否需要。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

喜你已久 2024-12-27 13:10:54

作为一个好的实践,是的,因为 equalshashCodecompareTo 具有接近的含义。它们可以被视为同一事物的不同方面。如果您的对象在其他地方使用而没有一起实现它们,您可能会遇到不可预测的行为。

例如,您已将对象传递给使用二分搜索算法的第三方库,它使用 compareTo。几个月后,该库的新版本更改为基于哈希的数据结构以提高性能,该结构依赖于 equalshashCode。从他们的角度来看,这并不是重大变化。

在本例中,不会,因为 DelayQueue 不使用它们。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文