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 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示