Your Address

赞助商

MOST RECENT NEWS - WE MOMENTARILY RENEW

1
      今天下午,有个朋友问我,下面的代码执行的结果:
  Integer k1 =5 ,k2 =5;
  Integer j1 =177 ,j2 =177;  
  System.out.println(k1==k2);
  System.out.println(j1==j2);

      你认为呢?既然这么问,肯定是有问题的。看了一下,然后打开java 的source(必须是later jdk1.5的版本,在jdk1.5以前 Integer j1 = 1;这样写会报错,这是因为1.5的自动装箱特性。),得出下面的结论:
      console输出的应该是true  和false 。
      那么下面的程序呢?      
  Integer k1 =5 ,k2 =5;
  Integer j1 =127 ,j2 =127;  
  System.out.println(k1==k2);
  System.out.println(j1==j2);

      这就当然是输出两个true了。ok下面解释为什么。
      首先看找到源代码中的IntegerCache这个类。
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[i] = new Integer(i - 128);
  }
}

      这个类维护了一个IntegerCache[]的数组,长度为256,即-128到127中间的数。这样,有助于提高程序的效率。
      对于用Integer 实例化的方法来赋值的变量,实际上是一个复杂类型数据对象(不像int double 等等这些的简单类型数据对象),但是看到上面的代码,当赋值还是一个在-128到127中间的数的时候,这样是直接调用缓存的,不属于这个范围的就是要实例化了。就相对于是:
      Integer j1 = new Integer(127);
      Integer j2 = new Integer(127);
      这样,你还认为j1==j2吗?

作者:博爱老头@博爱老头的草屋
地址:http://www.icnote.com/java-1_5-integer-int/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!

1 条评论 to “java中Integer和int”

life   2008/07/23 23:09
SUN搞什么,害死人shockanger
博爱老头 回复于 2008/07/23 23:12
呵呵。。。弄懂了就好。
分页: 1/1 第一页 1 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称  [注册]
密码  [游客无需密码]
网址
电邮
               

 

©2007-2012 IcNote.COM Theme by Youth work room