equals()without hashCode() [英] equals() without hashCode()

查看:84
本文介绍了equals()without hashCode()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只能实现equals()而不是hashCode(),如果我只需要比较对象而不打算将对象放入任何基于散列的容器中?

似乎所有的Java圣经都说这两个必须一起实施。 :($ / b>

我的顾虑:
- 如果我总是用equals()实现hashCode(),那么会有很多代码没有真正使用,并且没有单位测试覆盖(如果不使用,我不打算单元测试hashCode())
- 直到我将对象放入基于散列的容器时,我才知道如何查找对象。只有到那时我才能确定使用哪种散列策略。

可以,但你会打破总体合同等于,这会导致一些奇怪的错误,即使你不认为你在使用哈希代码,你传递对象的外部代码可能依赖于他们,即使它似乎不是基于散列的。如果你不打算给你的对象一个体面的散列方法,至少让它抛出一个运行时异常。最好给你的对象一个体面的hashCode ,但是。


Can I only implement equals() but not hashCode() if I only need to compare objects and not yet plan to put the objects into any hash based containers?

Seems all Java bibles say these two MUST be implemented together. :(

My concerns: -If I always implement hashCode() together with equals() there will be lots of code not really used, and without unit test covering. (I'm not going to unit test hashCode() if not used) -It's only until when I put the object into a hash based container I know how the objects are intended to be looked up. And only until then I can be sure which hashing strategy to use.

解决方案

You can, but you'll be breaking the general contract of equals, and this will lead to weird bugs. Even if you don't think you're using the hash codes, any external code you pass the objects to might rely on them, even if it doesn't seem to be hash-based. If you're not going to give your objects a decent hash method, at least make it throw a runtime exception. It's almost always better to give your objects a decent hashCode, though.

这篇关于equals()without hashCode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆