java hashcode 和 equals

Question: 如果一个类覆盖了Obejct 的 equals(Object) 方法,需要覆盖hashCode()方法吗?

A: 不强制覆盖, WARNING: 对于覆盖的equals中不要使用hashCode()方法; 对于hashCode方法实际都是计算比较重的方法;而equals方法一般都只是对象比较

 // Objects#hash
  public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }

// Arrays.hashCode
    public static int hashCode(Object a[]) {
        if (a == null)
            return 0;

        int result = 1;

        for (Object element : a)
            result = 31 * result + (element == null ? 0 : element.hashCode());

        return result;
    }

  

Question: 如果一个类覆盖了Object的hashCode()方法,需要覆盖equals(Object) 方法吗?

A: 必须要覆盖; 由于hashcode方法返回的数据为int,int的值最大2^31 - 1 , 存在范围的有限性,且由于hash的计算方法 也是存在hash冲突的可能性;  因此对于不同的对象由于hashcode有可能相同的情况,因此还需要通过equals方法进行对比;所以必须要重写equals方法

 

posted @ 2020-09-17 15:28  郭星  阅读(142)  评论(0)    收藏  举报