java基礎之易錯使用方式二

前言

今天要說的易錯點是關於java的8種基本類型的使用,很多初學者比較容易犯的錯誤,亦或是基礎不牢者也常常會犯,下面我們一起看一下,先從一個例子說起。

例子1

public class BugTest2 {
    public static void main(String[] args) {
        Integer a = 10;
        Integer b = 10;
        Integer c = 150;
        Integer d = 150;

        System.out.println(a == b);
        System.out.println(c == d);
    }
}

結果:

true
false

分析:

🙄,怎麼肥事???竟然一個是ture一個是false!!!我想基礎比較好的同學可能立馬能想到原因了,沒錯,就是你想的哪個。

出現這個結果的原因是:Byte、Short、Integer、Long、Char這幾個裝箱類的valueOf()方法是以128位分界線做了緩存的。

源碼:

這裏以Integer爲例,其他的類似。

/**
     * 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);
    }

我們可以看到註釋種這段話,This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range,意思就是說這個方法會緩存-128到127的整數。看到這裏我想大多數人應該都能明白爲什麼會出現true和fasle的原因了。

例子2

public class BugTest3 {
    public static void main(String[] args) {
        
        Double d1 = 10.0;
        Double d2 = 10.0;
        Double d3 = 150.0;
        Double d4 = 150.0;

        System.out.println(d1 == d2);
        System.out.println(d3 == d4);
    }
}

結果:

fasle
fasle

分析:

額額額,爲啥這次全是false了???一臉懵逼!原因其實很簡單,8種基本類型種,整型是放在緩存的,但是浮點型的就不是了,浮點型位數並不像整型那麼確定,無法有效的緩存起來。

源碼:

 /**
     * Returns a {@code Double} instance representing the specified
     * {@code double} value.
     * If a new {@code Double} instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Double(double)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  d a double value.
     * @return a {@code Double} instance representing {@code d}.
     * @since  1.5
     */
    public static Double valueOf(double d) {
        return new Double(d);
    }

從源碼種我們可以看到,是new了一個包裝類出來,而不是從什麼緩存種獲取的。Folat也是類似,同理。

溫馨提示:

如果我們想比較兩個數值是不是相等,盡力不要用“==”去比較而是用包裝類的equals()方法去比較,這樣可以避免出錯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章