Integer中==的怪现象

Integer这个家伙,使用==比较的时候,有时候为true,有时候是false。这是为什么?终于有一天,研究研究为什么这样,简单的例子:

package com.java.jvm;

public class IntegerTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		compare(10,10);//true
		compare(128,128);//false
//		Integer a = 10; 
//		System.out.println(a.hashCode());
//		Integer b = 10;
//		System.out.println(b.hashCode());
//		compare(a,10);//true
//		compare(a,b );//true
//		 a = 128;
//		 b = 128;
//		 compare(a,128); //false
//		compare(a,b); //false
	}
	
	public static void compare(Integer a , Integer  b){
		System.out.println(a==b);
	}

}
= =操作符比较的是操作符两端的操作数是否是同一个对象;另外= =操作符两边的操作数必须是同一类型的(可以是父子类之间)
= =比较的是地址。

那就说明上面Interger=10的对象地址相同,而Integer=128的对象地址不相同,这是怎么发生的呢?,Integer的源码:

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);
	}
    }

  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);
    }

valueOf(int i)返回一个表示指定的 int 值的 Integer 实例。如果不需要新的 Integer 实例,则通常应优先使用该方法,而不是构造方法 Integer(int),因为该方法有可能通过缓存经常请求的值而显著提高空间和时间性能。

Integer中IntegerCache有一个静态的Integer数组,在类加载时就将-128 到 127 的Integer对象创建了,并保存在cache数组中,一旦程序调用valueOf 方法,如果i的值是在-128 到 127 之间就直接在cache缓存数组中去取Integer对象。

原因找到了,现在看看其他的类型:

Boolean(全部缓存)

Byte(全部缓存)

Double(没有缓存)

Long(-128-127缓存)

Character(c <= 127 缓存)

Short(-128-127缓存)














转载于:https://my.oschina.net/winHerson/blog/132175

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值