Integer自动装箱拆箱bug,创建对象在-128到127

1

public class Demo3 {
	public static void main(String[] args) {
		Integer a = 1;
		Integer b = 2;
		Integer c = 128;
		Integer d = 128;
		Integer e = 321;
		Integer f = 321;
		Long g = 3L;
		System.out.println(System.identityHashCode(c));	//366712642
		System.out.println(System.identityHashCode(d));	//1829164700

		// 实际上在我们用Integer a = 数字;来赋值的时候Integer这个类是调用的public static Integer
		// valueOf(int i)这个方法。
		// public static Integer valueOf(int i) {
		// if(i >= -128 && i <= IntegerCache.high)
		// return IntegerCache.cache[i + 128];
		// else
		// return new Integer(i);
		// }
		// 我们来看看ValueOf(int
		// i)的代码,可以发现他对传入参数i做了一个if判断。在-128<=i<=127的时候是直接用的int原始数据类型,而超出了这个范围则是new了一个对象。我们//知道"=="符号在比较对象的时候是比较的内存地址,而对于原始数据类型是直接比对的数据值。那么这个问题就解决了。
		// 至于为什么用int型的时候值会在-128<=i<=127范围呢呢?我们知道八位二进制的表示的范围正好就是-128到127。大概就是因为这吧。

		System.out.println(c == d);// false
		System.out.println(e == f);// false
		System.out.println(c == (a + b));// false
		System.out.println(c.equals(a + b));// false
		System.out.println(g == (a + b));// true
		System.out.println(g.equals(a + b));// false 类型不一样

	}
}

  

posted @ 2014-12-07 09:48  wikiki  阅读(1245)  评论(0编辑  收藏  举报