对return IntegerCache.cache[i + 128];理解

		public static void main(String[] args) {
		    //第一组
			Double d1 =100d;
			Double d2=100d;
			System.out.println(d1==d2);
			//第二组
			Integer a1=100;
			Integer a2=100;
			System.out.println(a1==a2);
			//第三组
			Integer b1=150;
			Integer b2=150;
			System.out.println(b1==b2);
			//第四组
			Integer c1=-128;
			Integer c2=-128;
			System.out.println(c1==c2);
		}

执行结果:
false
true
false
true

第一组解释:
Double 和Float的 包装类不具备常量池概念,因此包装类的直接比较,其实比的是内存中的两个对象,结果为false。
Byte,Short,Integer,Long,Character。这5种整型的包装类的常量池范围在-128~127之间,也就是说, 超出这个范围的对象都会开辟自己的堆内存。 使用常量池的好处,不用频繁的去new对象,减少空间。

第二组解释:
Integer对象在比较大小的时候,会调用如下源码中的方法

	public static Integer valueOf(int i) {
		if (i >= -128 && i <= IntegerCache.high)
			return IntegerCache.cache[i + 128];
		else
			return new Integer(i);
	}

这是一个隐式的拆箱操作,如果i的范围在-128~127之间
将包装类对象Integer转成基本数据类型int去比较大小,点进去看IntegerCache实现


public final class Integer extends Number implements Comparable {
	private static class IntegerCache {

		static final int low = -128;
		static final int high;
		static final Integer cache[];
		static final boolean $assertionsDisabled;

		static {
			$assertionsDisabled = !java / lang / Integer.desiredAssertionStatus();
			int i = 127;
			String s = VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
			if (s != null)
				try {
					int j = Integer.parseInt(s);
					j = Math.max(j, 127);
					i = Math.min(j, 2147483518);
				} catch (NumberFormatException numberformatexception) {
				}
			high = i;
			cache = new Integer[(high - -128) + 1];
			int k = -128;
			for (int l = 0; l < cache.length; l++)
				cache[l] = new Integer(k++);

			if (!$assertionsDisabled && high < 127)
				throw new AssertionError();
		}

可以看见high=127
创建了一个cache = new Integer[(high - -128) + 1];长度为256的整型数组,
如果你声明了一个integr a=10;当你用a去比较大小时,
访问的是
return IntegerCache.cache[i + 128];,也就是数组cache[138]的值,cache数组放在static静态代码块中,静态代码块会在被访问的时候,加载到内存中,也就是有一个叫做cache的数组在内存中
由:

           int k = -128;
			for (int l = 0; l < cache.length; l++)
				cache[l] = new Integer(k++);

可知:
cache[0]=-128,
cache[1]=-127

cache[138]=10;
因此 intger a=10,在比较大小的时候,由于调用了valueOf()方法就是int a=10;

			Integer a1=100;
			Integer a2=100;
			System.out.println(a1==a2);

因此这个结果实际就是两个常量100比较大小,结果为true

第三组解释:

			Integer b1=150;
			Integer b2=150;
			System.out.println(b1==b2);

由于超过了-128到127的范围,因此返回的 return new Integer(i); 是两个Integer对象,这两个不同的对象之间比较,结果为false

第四组解释:

			Integer c1=-128;
			Integer c2=-128;
			System.out.println(c1==c2);

访问的都是常量池中的chche[0],结果一致,为true

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值