java裡的一些hash方法

sayWhat_sayHello發表於2019-03-04

HashMap

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h =key.hashCode()) ^ (h >>> 16);
}

HashMap裡的Node結點的hash方法

public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
}

Integer

public static int hashCode(int value) {
    return value;
}

Byte

public static int hashCode(byte value) {
    return (int)value;
}

Character

public final int hashCode() {
    //super指的是Object
    return super.hashCode();
}

Object

public native int hashCode();

String

public int hashCode() {
    //hash預設是0
    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;
}

Long

public static int hashCode(long value) {
    return (int)(value ^ (value >>> 32));
}

Double

public static int hashCode(double value) {
    long bits = doubleToLongBits(value);
    return (int)(bits ^ (bits >>> 32));
}

public static long doubleToLongBits(double value) {
     long result = doubleToRawLongBits(value);
     // Check for NaN based on values of bit fields, maximum
     // exponent and nonzero significand.
     if ( ((result & DoubleConsts.EXP_BIT_MASK) ==
           DoubleConsts.EXP_BIT_MASK) &&
          (result & DoubleConsts.SIGNIF_BIT_MASK) != 0L)
         result = 0x7ff8000000000000L;
     return result;
}

public static native long doubleToRawLongBits(double value);

public static final long SIGN_BIT_MASK = -9223372036854775808L;
public static final long EXP_BIT_MASK = 9218868437227405312L;
public static final long SIGNIF_BIT_MASK = 4503599627370495L;

相關文章