`

JAVA中的Integer

    博客分类:
  • java
阅读更多
首先:
Java代码
public static void main(String []args) {
     Integer a = 100;
     Integer b = 100;
     System.out.println(a==b);   //true
   }


Java代码
public static void main(String []args) {
     Integer a = 200;
     Integer b = 200;
     System.out.println(a==b);   //false
   }


原因:
1。java在编译的时候 Integer a = 100; 被翻译成-> Integer a = Integer.valueOf(100);
2。比较的时候仍然是对象的比较
3。在jdk源码中
Java代码
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); 
} 



Java代码
   private static class IntegerCache {    
   private IntegerCache(){}    
   static final Integer cache[] = new Integer[-(-128) + 127 + 1];    
   static {    
   for(int i = 0; i < cache.length; i++)    
   cache = new Integer(i - 128);    
   }    
   }   


这边是java为了提高效率,初始化了-128--127之间的整数对象
所以在赋值在这个范围内都是同一个对象。
再加一句
Integer a = 100;
a++;
//这边a++是新创建了一个对象,不是以前的对象。
Java代码
   public static void main(String []args) {   
      Integer a = 100;   
      Integer b = a;   
      a++;   
       System.out.println(a==b);   
   }  


打印就是false .
对于127--128没有多大关系,但是在这范围之外就影响性能了吧 !
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics