equals和hashcode的不同字段 [英] Different fields for equals and hashcode

查看:149
本文介绍了equals和hashcode的不同字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我同意这篇文章中的声明重写时应考虑哪些问题等于hashCode in Java?


使用您用来计算equals()来计算hashCode()的相同字段集合。


但我有些怀疑:


  • 这是绝对有必要有相同的领域?

  • 如果是的话,如果我不使用相同的字段?

  • 它会影响HashMap性能或HashMap精度吗?

解决方案


是否必须拥有相同的字段?


是的,如果你不想要任何意外。


如果是的话,如果我不使用相同的字段?


对于相同的对象,您可能获得不同的 hashCode code> equals()方法,这是equals和hashCode合约的要求。例如,假设你有3个字段 - a b c $ c>, c 。对于 equals()方法,您使用 a b ,以及 hashCode()方法的所有3个字段。因此,对于2个对象,如果 a b 是等于的,并且 c $ b


它会影响HashMap性能或HashMap精度吗?


这不是关于表现,而是你的地图不会像预期的那样表现。


I agree with the statement from this post What issues should be considered when overriding equals and hashCode in Java?

Use the same set of fields that you use to compute equals() to compute hashCode().

But i've some doubts :

  • Is this absolutely necessary to have same fields ?
  • If yes, what if I don't use same field ?
  • Will it affect HashMap performance or HashMap Accuracy ?

解决方案

Is this absolutely necessary to have same fields ?

Yes, if you don't want any surprises.

If yes, what if I don't use same field ?

You might get different hashCode for objects that are equal, as per equals() method, which is a requirement for the equals and hashCode contract.

For example, suppose you've 3 fields - a, b, c. And you use a and b for equals() method, and all the 3 fields for hashCode() method. So, for 2 objects, if a and b are equals, and c is different, both will be equals with different hashcode.

Will it affect HashMap performance or HashMap Accuracy ?

It's not about performance, but yes your map will not behave as expected.

这篇关于equals和hashcode的不同字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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