hashcode

HashCode

然后讲下什么是HashCode,总结几个关键点:

1、HashCode的存在主要是为了查找的快捷性,HashCode是用来在散列存储结构中确定对象的存储地址的

2、如果两个对象equals相等,那么这两个对象的HashCode一定也相同,反过来不成立,只能说明两个对象在同一位置。

3、如果对象的equals方法被重写,那么对象的HashCode方法也尽量重写。(是为了满足第二点,如果重写了equals方法,而hashcode方法不重写,可能导致两个对象equals但是hashcode不同,这是不允许的。)

Integer的hashcode方法:

public int hashCode() {
  return value;
}

String的hashcode方法:

public int hashCode() {
    int h = hash;
    if (h == 0) {
        int off = offset;
        char val[] = value;
        int len = count;

            for (int i = 0; i < len; i++) {
                h = 31*h + val[off++];
            }
            hash = h;
        }
        return h;
    }

hashmap中entry的hashcode方法:

public final int hashCode() {
      return (key==null   ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode());
}

  

原文地址:https://www.cnblogs.com/tp123/p/6395739.html