Java: Integer比较127, 128

Java: Integer用==比较时127相等128不相等的原因

Integer数值在 -128 到 127 之间是从缓存中去取值,所以返回的是同一个对象,可以直接Integer==Integer,且相等

当数值不在此范围内,则会返回新对象,==比较就会不相等,可以比较Integer.intValue() == Integer.intValue()

最后贴源码:

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

版权声明:本文为qq_27195727原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。