Integer 装箱 拆箱 比较

赋值操作

1.Integer与int类型的赋值

把Integer类型的赋值给int类型,调用intValue()方法进行拆箱赋值。

把int类型赋值给Integer,会调用valueOf()方法对int进行装箱赋值。

2.Integer与int类型的比较

先对Integer调用intValue()进行拆箱,然后进行值比较

比较操作

1.Integer之间的比较

对象比较

2.int之间的比较

进行值比较

valueOf()方法

valueOf()方法

/**
     * 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范围内的值。

在使用valueOf时,会判断i是否在-128~127范围内,如果在范围内,则从数组缓存中去;否则,新建。

在两个Integer进行比较的时候,一定要注意使用了valueOf()方法.

posted @ 2017-02-27 17:10  lion85  阅读(1182)  评论(0编辑  收藏  举报