hashCode方法總結

hashCodejava

public class Object {
    public native int hashCode(); // 是Object對象的方法,有默認實現,可是native的。由內存地址計算而來。
}

全部

的類要麼重寫hashCode方法,要麼調用Object的hashCode()方法。
數組

public class _hashCodeTest {
    public static void main(String[] args) {
        System.out.println(new Integer(10).hashCode());//數字,返回自身  10
        System.out.println(new Integer(-10).hashCode());//數字,返回自身  -10
        System.out.println(new Boolean(true).hashCode());//1237
        System.out.println(new Boolean(false).hashCode());//1231
        System.out.println("5".hashCode()); // 字符串 53
        System.out.println("50".hashCode()); //字符串 1691

        System.out.println(new Student().hashCode());// 自定義1314
        System.out.println(new _hashCodeTest().hashCode()); //沒有自定義,對象的內存地址計算而來
    }
}

class Student {
    @Override
    public int hashCode() {
        return 1314;
    }
}


Integer:ide

public final class Integer extends Number implements Comparable<Integer> {
    private final int value;
    public Integer(int value) {
        this.value = value;
    }
    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }
    //返回自身的值
    public static int hashCode(int value) {
        return value;
    }
}

Long類型:性能

public final class Long extends Number implements Comparable<Long> {
    //1 保證了 若是value在int範圍內,則hash值不變
public static int hashCode(long value) {
    return (int)(value ^ (value >>> 32)); // 若是在int範圍內,則高位的32位都是0, 經過無符號右移32位後,變爲0
    // 和原來的值作異或運算.(兩個操做數的位中,相同則結果爲0,不一樣則結果爲1).
}
    @Override
    public int hashCode() {
        return Long.hashCode(value);
    }
}


Boolean:優化

public final class Boolean implements java.io.Serializable,
                                      Comparable<Boolean> {
     @Override
    public int hashCode() {
        return Boolean.hashCode(value);
    }    
    //返回固定的值。true:1231 false:1237 , 爲何是這兩個數
    public static int hashCode(boolean value) {
        return value ? 1231 : 1237;
    }                                 
}

String類型:this

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    
        public int hashCode() {
        int h = hash;
        //1 hash做爲一個成員, 每次調用hashCode(), 都檢查h == 0,優化性能,避免重複計算
        if (h == 0 && value.length > 0) {
            char val[] = value;
           
            //2 遍歷整個字符數組
            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i]; //3 字符就是整數
            }
            hash = h;
        }
        return h;
    }
}
相關文章
相關標籤/搜索