Integer.valueOf 返回對象的差別

    System.out.println(Integer.valueOf("127")==Integer.valueOf("127")); --> **TRUE**
    System.out.println(Integer.valueOf("128")==Integer.valueOf("128")); --> **FALSE**
    原因是因爲Integer內部有緩存-128到127的小對象。
    public static Integer valueOf(String string) throws NumberFormatException {
        return valueOf(parseInt(string));
    }

    public static Integer valueOf(int i) {
        return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
    }
    /**
     * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing
     */
    private static final Integer[] SMALL_VALUES = new Integer[256];

    static {
        for (int i = -128; i < 128; i++) {
            SMALL_VALUES[i + 128] = new Integer(i);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章