为地址创建hashCode和equals

时间:2011-09-17 04:40:12

标签: java equals hashcode

我需要为equals() and hashCode()课程实施Address

我相信,非空字段用于确定hashCode()和equals()。在我的应用程序中,除addressLine1country之外的任何字段都可以为null。如果是如果两个不同的地址具有相同的addressline1和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

在这种情况下,如果我只基于非空字段构建一个hashCode,它将为上述两个地址提供相同的内容。

这是创建hashCode的正确方法吗?

int hash = addressline.hashCode();
if(addressLine2!=null){
   hash += addressLine2.hashCode();
}
and so on...

2 个答案:

答案 0 :(得分:2)

通常,您会检查一个是否为null而另一个不在您的equals方法中。对于哈希码,您只需使用0作为空哈希码。例如:

public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((addressLine1 == null) ? 0 : addressLine1.hashCode());
    result = prime * result + ((state == null) ? 0 : state.hashCode());
    result = prime * result + ((country == null) ? 0 : country.hashCode());
    return result;
}

如果您使用IDE,它通常会为您生成这些。在eclipse中,选择Source,Generate equals和hashcode,它将允许您选择要作为equals和hashcode方法一部分的字段。对于equals方法和您的字段,这就是eclipse创建的内容:

public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null) return false;
    if (getClass() != obj.getClass()) return false;
    YourClass other = (YourClass) obj;
    if (addressLine1 == null) {
        if (other.addressLine1 != null) return false;
    } else if (!addressLine1.equals(other.addressLine1)) return false;
    if (country == null) {
        if (other.country != null) return false;
    } else if (!country.equals(other.country)) return false;
    if (state == null) {
        if (other.state != null) return false;
    } else if (!state.equals(other.state)) return false;
    return true;
}

我会以此作为起点,并从那里做出你认为必要的任何改变。

答案 1 :(得分:1)

即使是null的字段也应该进行相等性比较。使用如下代码   比较两个非原始类型的字段,如String:

this.addressline==null ? other.addressline==null : this.addressline.equals(other.addressline)

对于哈希码,请使用您在equals中使用的相同字段,但可以将空值视为 哈希码为0(或任何其他哈希码值)。

以下是规范问题:

What issues should be considered when overriding equals and hashCode in Java?

以下是有助于您正确实施这些方法的库的讨论:

Apache Commons equals/hashCode builder(也讨论番石榴)

相关问题