HelloWorld 善战者,求之于势,不责于人;故能择人而任势。

知止而后有定,定而后能静,静而后能安,安而后能虑,虑而后能得。物有本末,事有终始。知所先后,则近道矣。

  BlogJava :: 首页 ::  :: 联系 ::  :: 管理 ::
  167 随笔 :: 1 文章 :: 40 评论 :: 0 Trackbacks
package com.test;
public class 解包装包 {
   public static void main(String []args) {
     Integer a = 100;
     Integer b = 100;
     System.out.println(a==b);
   }
}
打印结果为:true
但是如果换成 128 > var >= -128 之外的整数就打false了。
这是什么原因呢?
1。java在编译的时候 Integer a = 100; 被翻译成-> Integer a = Integer.valueOf(100);
2。比较的时候仍然是对象的比较
3。在jdk源码中
。。。
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);
}
。。。

。。。
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++是新创建了一个对象,不是以前的对象。
    public static void main(String []args) {
        Integer a = 100;
        Integer b = a;
        a++;
        System.out.println(a==b);
    }
打印就是false

对于127--128没有多大关系,但是在这范围之外就影响性能了吧,就像StringBuffer VS String一样了


</script>

posted on 2007-08-13 18:50 helloworld2008 阅读(2855) 评论(0)  编辑  收藏 所属分类: java

只有注册用户登录后才能发表评论。


网站导航: