您的位置:首页 > 编程语言 > Java开发

Integer初始赋值后对象之间==操作详细解析

2016-11-03 12:23 453 查看
先看下面一段有意思的代码,来检测一下自己的基本功:

Integer a = 1000;
Integer b = 1000;
Integer c = 100;
Integer d = 100;
System.out.println(a == b);
System.out.println(c == d);
如果你能得出正确答案,并理解其中的原理,那你的基础还不错,至少在理解Integer对象上还不错。如果你的答案是true,true那证明还所欠缺,对象进行==比较时,比较的是对象的地址值。

正确答案是false,true;其实原理还是挺简单的,就是可能没有去了解和看过Integer.java这个源码了,下面来揭开Integer的面纱;

当声明一个Integer a = 1000时,是会进行自动封装操作的,就是把基础数据类型转换成封装对象类型,而此时就需要自动调用Integer的valueOf(int i)方法:

/**
         * 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) {
            assert IntegerCache.high >= 127;
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                //当为-128和127之间时,并没有new一个Integer,而是从缓存中取
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }





这个方法返回的是一个Integer的对象类型,This method will always cache values in the range -128 to 127,这个方法总是从缓存中取-128至127之间的数据,我们再来看一下IntegerCache类的cache数组:

private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];

static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}

private IntegerCache() {}
}


这个类是Integer的一个静态内部类,中间定义了一个三个常量low,hight,cache分别代表最低值,最高值,Integer缓存数组,将-128至127之间的数字,全部构造成了Integer类型装入这个数组中。

到这里相信大家已经基本明白了,当我们申明一个Integer类型的变量,值处在-128至127之间时,总是从cache这个数组中取值,所以导致取出来的是同一个对象,这样做了就如数组名称一样cache,保证这些频繁使用的小数值Integer对象不用重新创建,直接获取,以用来提高性能。当申明对象的值超出了这个范围则是每次重新创建一个对象出来,新创建的两个对象的地址值就肯定不是一样的了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java integer 比较