1. 程式人生 > 其它 >hashCode() vs equals() vs ==

hashCode() vs equals() vs ==

== VS equals()

==
  • 基礎型別: ==比較的是值
  • 引用型別: ==比較的是物件的記憶體地址
equals()

equals()只能比較引用型別,無法比較基礎型別.equals()方法在頂級父類Object中,程式碼如下:

    public boolean equals(Object obj) {
        return (this == obj);
    }

可以看出這個程式碼就是判斷是否是同一物件.那麼,當子類重寫 equals()往往都是將屬性內容相同的物件認為是同一物件,
如果子類不直接或間接重寫Objectequals()方法,那麼呼叫的equals()

==相同.

String a = new String("aa"); // a 為一個引用
String b = new String("aa"); // b為另一個引用,物件的內容一樣
String aa = "aa"; // 放在常量池中
String bb = "aa"; // 從常量池中查詢
System.out.println(aa == bb);// true
System.out.println(a == b);// false
System.out.println(a.equals(b));// true

上面程式碼的String重寫了equals(),程式碼如下:

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

hashCode() VS equals()

  • hashCode()函式返回雜湊碼,確定該物件在雜湊表中的索引位置.同樣屬於Object類中,程式碼如下:
    public native int hashCode();,native呼叫C/C++,返回int雜湊碼.利用雜湊碼能夠快速檢索出物件
    HashSet/HashMap會先呼叫hashCode(),如果雜湊碼不同,直接判斷物件不同,否則進行下面的equals()操作,大大減少了equals()的操作,提高執行速度.(C/C++本身比Java執行快,equals()執行也比hashCode()邏輯複雜)
  • hashCode()返回值相同也不能認為是同一物件,存在hash衝突
  • hashCode 相同,equals()為true才能認為是同一物件
為什麼重寫 equals() 時必須重寫 hashCode() 方法?
  • 正面:兩物件相等,那麼hashCode也相等,equals()也為true
  • 反面:重寫 equals(),但是不重寫hashCode(),會導致equals(),判斷是同一個物件,但是雜湊碼並不同
  • 例子: 重寫了equals()方法,不重寫hashCode(),同一名學生,新增到hashSet中時候,會新增兩次,因為你只是通過屬性內容判斷的是否為同一物件!!!

包裝型別的常量池

  • Byte/Short/Integer/Long 這 4 種包裝類預設建立了數值 [-128,127] 的相應型別的快取資料
  • Character 建立了數值在 [0,127] 範圍的快取資料
  • Boolean 直接true/false
    原始碼如下:
    private static class ByteCache {
    private ByteCache(){}

    static final Byte cache[] = new Byte[-(-128) + 127 + 1];

    static {
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Byte((byte)(i - 128));
    }
}

    /**
     * Returns a {@code Byte} instance representing the specified
     * {@code byte} value.
     * If a new {@code Byte} instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Byte(byte)}, as this method is likely to yield
     * significantly better space and time performance since
     * all byte values are cached.
     *
     * @param  b a byte value.
     * @return a {@code Byte} instance representing {@code b}.
     * @since  1.5
     */
    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }
    private static class ShortCache {
    private ShortCache(){}

    static final Short cache[] = new Short[-(-128) + 127 + 1];

    static {
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Short((short)(i - 128));
    }
}

    /**
     * Returns a {@code Short} instance representing the specified
     * {@code short} value.
     * If a new {@code Short} instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Short(short)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  s a short value.
     * @return a {@code Short} instance representing {@code s}.
     * @since  1.5
     */
    public static Short valueOf(short s) {
        final int offset = 128;
        int sAsInt = s;
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }
private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
private static class LongCache {
        private LongCache(){}

        static final Long cache[] = new Long[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Long(i - 128);
        }
    }

    /**
     * Returns a {@code Long} instance representing the specified
     * {@code long} value.
     * If a new {@code Long} instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Long(long)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * Note that unlike the {@linkplain Integer#valueOf(int)
     * corresponding method} in the {@code Integer} class, this method
     * is <em>not</em> required to cache values within a particular
     * range.
     *
     * @param  l a long value.
     * @return a {@code Long} instance representing {@code l}.
     * @since  1.5
     */
    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }

上面的快取程式碼可以完美解釋下面的結果:

Integer a = 10;
Integer b = 10;
System.out.println(a == b);// 輸出 true

Float c = 10f;
Float d = 10f;
System.out.println(c == d);// 輸出 false

Double e = 1.2;
Double f = 1.2;
System.out.println(e == f);// 輸出 false

Integer a = 10;
Integer b = new Integer(10);
System.out.println(a==b);// false
//Integer a = 10;=>Integer a=Integer.valueOf(10);使用常量池中的物件,Integer b = new Integer(10);建立新物件

自動裝箱與拆箱

從位元組碼中,我們發現裝箱其實就是呼叫了 包裝類的valueOf()方法,拆箱其實就是呼叫了 xxxValue()方法。

  • Integer i = 1 等價於 Integer i = Integer.valueOf(1)
  • int n = i 等價於 int n = i.intValue();
  • 如果頻繁拆裝箱的話,也會嚴重影響系統的效能。我們應該儘量避免不必要的拆裝箱操作。