iteye_16766 2009-05-12 13:54
浏览 308
已采纳

重写hashCode() 问题,结果为什么是0而不是17?

public class LabelValue {
private String label;
private String value;

public LabelValue(final String label, final String value) {
    this.label = label;
    this.value = value;
}

public String getLabel() {
    return this.label;
}

public void setLabel(String label) {
    this.label = label;
}

public String getValue() {
    return this.value;
}

public void setValue(String value) {
    this.value = value;
}

public int hashCode() {
    return (this.getValue() == null) ? 17 : this.getValue().hashCode();
}

public boolean equals(Object obj) {
    if (obj == this) {
        return true;
    }
    if (!(obj instanceof LabelValue)) {
        return false;
    }
    LabelValue bean = (LabelValue) obj;
    int nil = (this.getValue() == null) ? 1 : 0;
    nil += (bean.getValue() == null) ? 1 : 0;
    if (nil == 2) {
        return true;
    } else if (nil == 1) {
        return false;
    } else {
        return this.getValue().equals(bean.getValue());
    }

}

}

public class MyResult {
public static void main(String[] args) {
LabelValue lv1 = new LabelValue("1","router");
LabelValue lv2 = new LabelValue("2","switch");
LabelValue lv3 = new LabelValue("3","router");
LabelValue lv4 = new LabelValue("4","");
System.out.println(lv4.hashCode());
}

}

  • 写回答

1条回答 默认 最新

  • lggegegmail 2009-05-12 16:34
    关注

    [code="java"]""[/code]
    是空字符串, "" != null , 所以, 得到的是 "".hashCode(),

    String.hashCode()算法如下, 可以去看String.hashCode()方法的注释,
    [code="java"]
    s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
    [/code]

    于是得到0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)