Integer使用==需要注意的地方

/*Integer比较-128—127的数值时可以直接用==,这个时候是直接从缓存里面取的同一个对象*/
        Integer a = 1000,b=1000;  
        Integer c = 100,d=100;  
        System.out.println(a==b);  
        System.out.println(c==d);

 输出的正确结果分别是  falsetrue

public static Integer valueOf(int arg) {
        return arg >= -128 && arg <= Integer.IntegerCache.high ? Integer.IntegerCache.cache[arg + 128] : new Integer(arg);
    }
private static class IntegerCache {
        static final int       low = -128;
        static final int       high;
        static final Integer[] cache;

        static {
            int arg = 127;
            String arg0 = VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            int arg1;
            if (arg0 != null) {
                try {
                    arg1 = Integer.parseInt(arg0);
                    arg1 = Math.max(arg1, 127);
                    arg = Math.min(arg1, 2147483518);
                } catch (NumberFormatException arg3) {
                    ;
                }
            }

            high = arg;
            cache = new Integer[high - -128 + 1];
            arg1 = -128;

            for (int arg2 = 0; arg2 < cache.length; ++arg2) {
                cache[arg2] = new Integer(arg1++);
            }

            assert high >= 127;

        }
    }

当声明Integer a=100 的时候,会进行自动装箱操作,即调用 valueOf() 把基本数据类型转换成Integer对象,valueOf()方法中可以看出,

程序把 -128—127之间的数缓存下来了(比较小的数据使用频率较高,为了优化性能),所以当Integer的对象值在-128—127之间的时候是

使用的缓存里的同一个对象,所以结果是true,而大于这个范围的就会重新new对象。

Integer a = new Integer(1000);  
int b = 1000;  
Integer c = new Integer(10);  
Integer d = new Integer(10);  
System.out.println(a == b);  
System.out.println(c == d); 

  输出的正确结果分别是 truefalse

第一个:值是1000,肯定和缓存无关,但是b的类型是int,当int和Integer进行 == 比较的时候 ,java会将Integer进行自动拆箱操作,

再把Integer转换成int,所以比较的是int类型的数据,   so 是true

第二个:虽然值是10 在缓存的范围内,但是 c,d都是我们手动new出来的,不需要用缓存, so 是false

还有种情况

Integer a =100;
Integer b = new Integer(100);
System.out.println(a == b);

 这个时候的结果还是false,因为b是new出来使用了新的数据地址,而100使用的是缓存中的地址

Integer a =100;//java在编译的时候,被翻译成-> Integer a = Integer.valueOf(100)

猜你喜欢

转载自wzw5433904.iteye.com/blog/2316853