1. 程式人生 > >java8 hash算法

java8 hash算法

throw 數字 計算 const += this key 轉換成 查找

一、hash算法

  哈希算法將任意長度的二進制值映射為較短的固定長度的二進制值,這個小的二進制值稱為哈希值。哈希值是一段數據唯一且極其緊湊的數值表示形式。如果散列一段明文而且哪怕只更改該段落的一個字母,隨後的哈希都將產生不同的值。要找到散列為同一個值的兩個不同的輸入,在計算上是不可能的,所以數據的哈希值可以檢驗數據的完整性。一般用於快速查找和加密算法。

二、jdk的hash算法實現

(1)Interger

    private final int value;

    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }
public static int hashCode(int value) { return value; }

Integer的hash算法就是直接獲取它的數值。int整數範圍很大,分散廣沖突小。

(2)Short

    private final short value;

    @Override
    public int hashCode() {
        return Short.hashCode(value);
    }

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

(3)Byte

    private final byte value;

    @Override
    public int hashCode() {
        return Byte.hashCode(value);
    }

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

(4)Long

    private final long value;

    @Override
    public int
hashCode() { return Long.hashCode(value); } public static int hashCode(long value) { return (int)(value ^ (value >>> 32)); }

long類型作為索引範圍太大,需要轉為int類型。這裏簡單的獲取低32位容易導致散列不均,因為高位部分沒有被利用。所以這裏采用邏輯右移32位,讓高32位和低32位進行XOR操作,導致高位低位都能被利用到

(5)Double

    private final double value;

    @Override
    public int hashCode() {
        return Double.hashCode(value);
    }

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

由於double不能當成索引,所以需要轉換成整數

由於double數據類型底層采用64位bit碼表示,采用IEEE浮點標準編碼。如果將它使用8字節整數編碼方式,就能獲取一個long類型的數字

long類型作為索引範圍太大,需要轉為int類型。這裏簡單的獲取低32位容易導致散列不均,因為高位部分沒有被利用。所以這裏采用邏輯右移32位,讓高32位和低32位進行XOR操作,導致高位低位都能被利用到

最後得到的數字強轉int,只保留已經被充分打亂的低32位

(6)Float

     private final float value;

    @Override
    public int hashCode() {
        return Float.hashCode(value);
    }

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

    public static int floatToIntBits(float value) {
        int result = floatToRawIntBits(value);
        // Check for NaN based on values of bit fields, maximum
        // exponent and nonzero significand.
        if ( ((result & FloatConsts.EXP_BIT_MASK) ==
              FloatConsts.EXP_BIT_MASK) &&
             (result & FloatConsts.SIGNIF_BIT_MASK) != 0)
            result = 0x7fc00000;
        return result;
    }

    public static native int floatToRawIntBits(float value);
public class FloatConsts {
    public static final int EXP_BIT_MASK = 2139095040;
    public static final int SIGNIF_BIT_MASK = 8388607;
    //...
}

(7)Boolean

    private final boolean value;

    @Override
    public int hashCode() {
        return Boolean.hashCode(value);
    }

    public static int hashCode(boolean value) {
        return value ? 1231 : 1237;
    }

(8)Character

    private final char value;

    @Override
    public int hashCode() {
        return Character.hashCode(value);
    }

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

(9)String

    private final char value[];

    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;
    }

(10)Object

    public native int hashCode();

(11)自定義對象

public class Node<T> {

    private T data;
    private Node<T> next = null;
    
    @Override
    public int hashCode() {
        int hash = 3;
        hash = 97 * hash + Objects.hashCode(this.data);
        hash = 97 * hash + Objects.hashCode(this.next);
        return hash;
    }
}
public final class Objects {
    public static int hashCode(Object o) {
        return o != null ? o.hashCode() : 0;
    }
    //...
}

(12)HashMap

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

    public int hashCode() {
        int h = 0;
        Iterator<Entry<K,V>> i = entrySet().iterator();
        while (i.hasNext())
            h += i.next().hashCode();
        return h;
    }

(13)Hashtable

   public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }

    public synchronized int hashCode() {

        int h = 0;
        if (count == 0 || loadFactor < 0)
            return h;  // Returns zero

        loadFactor = -loadFactor;  // Mark hashCode computation in progress
        Entry<?,?>[] tab = table;
        for (Entry<?,?> entry : tab) {
            while (entry != null) {
                h += entry.hashCode();
                entry = entry.next;
            }
        }

        loadFactor = -loadFactor;  // Mark hashCode computation complete

        return h;
    }

java8 hash算法