Integer中=和new 创建的区别

1、new 无疑会调用构造方法,指定内存中新开辟的空间,两个Integer不是同一个实例对象。又 == 判断的是引用,所有会返回false。但equals重写了,比较的是值,所以返回的是true。源码如下

public int intValue() {
   return value;
}

public Integer(int value) {
   this.value = value;
}

public Integer(int value) {
  this.value = value;
}

private final int value;

public boolean equals(Object obj) {
   if (obj instanceof Integer) {
     return value == ((Integer)obj).intValue();
    }
  return false;
}

2、= 创建

Integer中的静态内部类 IntegerCache,缓存。

Java 编译器把原始类型自动转换为封装类的过程称为自动装箱(autoboxing),这相当于调用 valueOf 方法

public static Integer valueOf(int i) {  

if (i >= IntegerCache.low && i <= IntegerCache.high)  

  return IntegerCache.cache[i + (-IntegerCache.low)];  //溢出计算,得到的对应索引

   return new Integer(i);  //不在-128~127的,都是创建的新对象

public static final int MAX_VALUE = 0x7fffffff;//2147483647对应的16进制数

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;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - (-low));
        }
        high = h;	//  high=127

        cache = new Integer[(high - low) + 1];   //	cache	=new Integer[256];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);	//提前把 -128~127的实例对象实例化好了,所以怎么取都是同一个
    }

    private IntegerCache() {}
}

总结:Integer赋值时,只要是new的,肯定是一个新对象;而 = 赋值的话,范围在 -128~127,就是同一个对象;超出范围都是新对象。

equals比较的是值是否相等。

 

Long类型 也缓存了 -128~127

private static class LongCache { 
private LongCache(){}
 static final Long cache[] = new Long[-(-128) + 127 + 1];
 static { 
    for(int i = 0; i < cache.length; i++) 
          cache[i] = new Long(i - 128); 
     } 
}

 Short类型 也缓存了 -128~127

private static class ShortCache { 
     private ShortCache(){} static final Short cache[] = new Short[-(-128) + 127 + 1];
      static { 
          for(int i = 0; i < cache.length; i++) 
           cache[i] = new Short((short)(i - 128)); 
   }
 }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值