new Integer 和 Integer.valueOf 有什么不同
生活随笔
收集整理的这篇文章主要介绍了
new Integer 和 Integer.valueOf 有什么不同
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
2019独角兽企业重金招聘Python工程师标准>>>
@Testpublic 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
总结
以上是生活随笔为你收集整理的new Integer 和 Integer.valueOf 有什么不同的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: ZigBee TI ZStack CC2
- 下一篇: OPPO R11巴萨限量版开售,上午10