Java中Integer的valueOf方法,-128到127的整数将被缓存

Java中int和Integer使用==比较将Integer拆箱成int后比较大小(jdk版本不小于1.5)
Integer和Integer之间==比较,是对象之间的比较,看两个引用是否指向同一个内存地址
但是一个字节的整数-128到127之间的整数将被缓存至IntegerCache
所有一个字节大小的Integer都存储于IntegerCache中,new创建的除外
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
     	...
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

      	...
    }

    private IntegerCache() {}
}


在jdk1.5的环境下,有如下4条语句:
1
2
3
4
Integer i01 =  59 ;
int i02 =  59 ;
Integer i03 =Integer.valueOf( 59 );
Integer i04 =  new Integer( 59 )。

以下输出结果为false的是:

System.out.println(i01== i02);
System.out.println(i01== i03);
System.out.println(i03== i04);
System.out.println(i02== i04);

Integer i01=59;
int i02=59;
Integer i03=Integer.valueOf(59);
Integer i04=new Integer(59);
System.out.println(i01==i02);
System.out.println(i01==i03);
System.out.println(i01==i04);
System.out.println(i02==i02);
"D:\Program Files\Java\jdk1.8.0_45\bin\java"...
true
true
false
true


Process finished with exit code 0

Integer i01=59 的时候,会调用 Integer 的 valueOf 方法,

1
2
3
4
5
   public static Integer valueOf( int i) {
      assert IntegerCache.high>=  127 ;
      if (i >= IntegerCache.low&& i <= IntegerCache.high)
      return IntegerCache.cache[i+ (-IntegerCache.low)];
      return new Integer(i); }

这个方法就是返回一个 Integer 对象,只是在返回之前,看作了一个判断,判断当前 i 的值是否在 [-128,127] 区别,且 IntegerCache 中是否存在此对象,如果存在,则直接返回引用,否则,创建一个新的对象。

在这里的话,因为程序初次运行,没有 59 ,所以,直接创建了一个新的对象。

 

int i02=59 ,这是一个基本类型,存储在栈中。

 

Integer i03 =Integer.valueOf(59); 因为 IntegerCache 中已经存在此对象,所以,直接返回引用。

 

Integer i04 = new Integer(59) ;直接创建一个新的对象。

 

System. out .println(i01== i02); i01 是 Integer 对象, i02 是 int ,这里比较的不是地址,而是值。 Integer 会自动拆箱成 int ,然后进行值的比较。所以,为真。

 

System. out .println(i01== i03); 因为 i03 返回的是 i01 的引用,所以,为真。

 

System. out .println(i03==i04); 因为 i04 是重新创建的对象,所以 i03,i04 是指向不同的对象,因此比较结果为假。

 

System. out .println(i02== i04); 因为 i02 是基本类型,所以此时 i04 会自动拆箱,进行值比较,所以,结果为真。


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值