為什么不要使用==比較Integer?


比較Integer的時候,不要用==。
查看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);
    }

通過注釋可以知道,為了更好的空間和時間性能,Integer會緩存頻繁使用的數值,數值范圍為-128到127,在此范圍內直接返回緩存值。
IntegerCache.low 是-128,IntegerCache.high是127,如果在這個區間內,他就會把變量i當做一個變量,放到內存中;
但如果不在這個范圍內,就會去new一個Integer對象,
而如果兩個Integer值都不在這個范圍內,那么就會new了兩個對象實例,兩個對象用==比較肯定是false。

解決方法

比較Integer的值有兩種方法,
1.一個是用equals()比較,但是注意要判空,避免空指針異常。
2.一個是用intValue()轉成int比較。
示例如下:

        Integer value1=129;
        Integer value2=129;
        if(value1.intValue()==value2.intValue()){
            // ...
        }

參考資料:
https://blog.csdn.net/luohao_/article/details/86607686


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM