为地址创建 hashCode 和 equals
我需要为 Address
类实现 equals() 和 hashCode()
。
我相信,非空字段用于确定 hashCode() 和 equals()。在我的应用程序中,除了 addressLine1
和 country
之外的任何字段都可以为空。如果是这样的,如果两个不同的地址具有相同的addressline1和国家,会发生什么?
Address1:(in state of NH which is omitted by user)
addressline1:111,maple avenue
country: US
Address2:
addressline1:111,maple avenue
state: Illinois
country: US
在这种情况下,如果我仅基于非空字段构建 hashCode,它将为上面的两个地址提供相同的值。
这是创建 hashCode 的正确方法吗?
int hash = addressline.hashCode();
if(addressLine2!=null){
hash += addressLine2.hashCode();
}
and so on...
I need to implement equals() and hashCode()
for an Address
class.
I believe,the non null fields are taken to determine hashCode() and equals().In my application,Any of the fields except addressLine1
and country
can be null.If that is the case,what happens if two different addresses have the same addressline1 and country?
Address1:(in state of NH which is omitted by user)
addressline1:111,maple avenue
country: US
Address2:
addressline1:111,maple avenue
state: Illinois
country: US
In such cases if I build a hashCode based only on non null fields ,it will give same for both addresses above.
Is this the right way to create hashCode?
int hash = addressline.hashCode();
if(addressLine2!=null){
hash += addressLine2.hashCode();
}
and so on...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,您会检查一个是否为 null,而另一个是否不在您的 equals 方法中。对于哈希码,您只需使用 0 作为空哈希码。示例:
如果您使用 IDE,它通常会为您生成这些。在 Eclipse 中,选择 Source、Generate equals 和 hashcode,它会让您选择想要成为 equals 和 hashcode 方法一部分的字段。对于 equals 方法和您的字段,这就是 eclipse 创建的内容:
我将使用它作为起点,并从那里进行您认为必要的任何更改。
Typically you would check whether one is null and the other is not in your equals method. For hashcode, you would just use 0 as the null hashcode. Example:
If you use an IDE, it will usually generate these for you. In eclipse, choose Source, Generate equals and hashcode and it will let you select the fields you want to be a part of your equals and hashcode methods. For the equals method and your fields, this is what eclipse creates:
I would use that as a starting point and make any changes you think are neccessary from there.
即使字段为空,也应该比较是否相等。使用如下代码
比较两个非基本类型的字段,例如字符串:
对于哈希码,请使用与 equals 中使用的相同字段,但可以将 null 值视为
哈希码为 0(或任何其他哈希码值)。
这是规范问题:
在 Java 中重写 equals 和 hashCode 时应考虑哪些问题?
以下是对帮助您正确实现这些方法的库的讨论:
Apache Commons equals/hashCode 构建器(还讨论了 Guava)
Even fields that are null should be compared for equality. Use code like the following
to compare two fields of nonprimitive types, like String:
For hash codes, use the same fields you used in equals, but you can treat null values as
having a hash code of 0 (or any other hash code value).
Here's the canonical question:
What issues should be considered when overriding equals and hashCode in Java?
And here are discussions of libraries that help you implement these methods properly:
Apache Commons equals/hashCode builder (also discusses Guava)