日期:2014-05-20  浏览次数:20681 次

一個問題,大家來看看(不容錯過)
public   class   WoDeGongJu18   {
        public   static   void   main(String[]   args)   {
                Integer   i1   =   100;
                Integer   i2   =   100;
                if   (i1   ==   i2)  
                        System.out.println( "i1   ==   i2 ");
                else  
                        System.out.println( "i1   !=   i2 ");
        }
}
public   class   WoDeGongJu19   {
        public   static   void   main(String[]   args)   {
                Integer   i1   =   200;
                Integer   i2   =   200;
                if   (i1   ==   i2)  
                        System.out.println( "i1   ==   i2 ");
                else  
                        System.out.println( "i1   !=   i2 ");
        }
}

兩個程序運行什麼結果?一樣嗎?為什麼?

加入:
我的工具-Java[18]   群號33323986
我的工具-Java[19]   群號38612890
共同研究JAVA,討論問題,幫你解決學習,工作等遇到的JAVA問題

說明:
都是120人上線的群

------解决方案--------------------
java.lang.Integer中关于valueOf的源代码是这样的:
public static Integer valueOf(int i) {
final int offset = 128;
if (i > = -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}

如果值在-128到127之间,会将其cached(缓存)起来,如果多次使用的话,会节省内存和改善性能;如果不在这个范围之内,则生成一个新的Integer Object instance,这样如果进行“==”时,由于是比较两个不同的Object references,故结果是false。
------解决方案--------------------
第一个是:i1 == i2
第二个是:i1 != i2
这个是关于自动包装的问题,还涉及到Integer类的范围

超过127,Integer类自动包装就有问题了