new Integer 和 Integer.valueOf 有什么不同

    @Test
	public void testHashCode() throws Exception {
		//[1237514926=acode, 1237514926=ccode, 548246552=bcode, 835648992=dcode]
		//可以看到 a 和 c 是同一个对象
		Integer a=9;
		Integer b=new Integer(9);
		Integer c=Integer.valueOf(9);
		Integer d=new Integer("9");
		int acode=System.identityHashCode(a);
		int bcode=System.identityHashCode(b);
		int ccode=System.identityHashCode(c);
		int dcode=System.identityHashCode(d);
		List<String> codeList=new ArrayList<>();
		codeList.add(acode+"=acode");
		codeList.add(bcode+"=bcode");
		codeList.add(ccode+"=ccode");
		codeList.add(dcode+"=dcode");
		Collections.sort(codeList);
		System.out.println(codeList);
		
		//[1134517053=acode, 1368884364=ccode, 401625763=dcode, 492228202=bcode]
		//如果值换为了128, 结果 a 和 c 就变成了不同对象, 这是因为 Integer 的实现原理, 
		/**
		 * 使用 new(int x) 创建对象的时候, 如下, 会创建新对象:
		 * public Integer(int value) {
         *     this.value = value;
         * }
         * 
         * Integer.valueOf(int x) 方法源码如下, 如果 x 在 IntegerCache.low 和 IntegerCache.high 
         * (-128~127)之间,会直接从 IntegerCache.cache[] 数组里面取, 也就是说是基本类型数值 x=9 ,而
         * 下面的128超出了这个范围,会调用构造器创建新对象 :
         * public static Integer valueOf(int i) {
	     *  	if (i >= IntegerCache.low && i <= IntegerCache.high)
	     *       	return IntegerCache.cache[i + (-IntegerCache.low)];
	     *   	return new Integer(i);
    	 * }
		 */
		a = 128;
		b = new Integer(128);
		c = Integer.valueOf(128);
		d = new Integer("128");
		acode = System.identityHashCode(a);
		bcode = System.identityHashCode(b);
		ccode = System.identityHashCode(c);
		dcode = System.identityHashCode(d);
		codeList = new ArrayList<>();
		codeList.add(acode + "=acode");
		codeList.add(bcode + "=bcode");
		codeList.add(ccode + "=ccode");
		codeList.add(dcode + "=dcode");
		Collections.sort(codeList);
		System.out.println(codeList);
	}

 

转载于:https://my.oschina.net/wliming/blog/1512257

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值