JAVA programming hashCode notes

definition:

hashCode is to extract a 32-bit integer based on all the data stored in an object instance. The purpose of the integer is to indicate the uniqueness of the instance; a bit similar to the MD5 code, each file can be generated by the MD5 algorithm A unique MD5 code. However, the hashCode in Java does not actually generate a unique hashCode for each object, and there will still be a certain chance of repetition

public native int hashCode();

The basis for hash code generation

Hash codes are not completely unique. It is an algorithm that allows objects of the same class to have different hash codes according to their different characteristics, but it does not mean that different objects have completely different hash codes. There is also the same situation, depending on how the programmer writes the algorithm of the hash code; usually, this value is a number composed of a part of the binary bits of the object header. This number has a certain meaning to identify the object, but it is by no means equivalent. at the address;

The role of hashCode

In order to generate a number that can identify an object, an object no matter how complex can be identified by a number;

Knowledge point

  • The String class uses its value as a parameter to calculate the hashCode
public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}
  • Different objects may generate the same hashcode
String a = "Aa";
String b = "BB";
System.out.println(a.hashCode());
System.out.println(b.hashCode());
  • The return value of the object.hashCode() method is the same as the return value of System.identityHashCode by default

  • JDK8 HashMap hash algorithm

static final int hash(Object key) {   //jdk1.8 & jdk1.7
     int h;
     // h = key.hashCode() 为第一步 取hashCode值
     // h ^ (h >>> 16)  为第二步 高位参与运算
     return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

HashMap如何计算数组索引
(length - 1) & hash //length是数组长度

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325546666&siteId=291194637