new Integer 和 Integer.valueOf 有什么不同
生活随笔
收集整理的這篇文章主要介紹了
new Integer 和 Integer.valueOf 有什么不同
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
@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, 結(jié)果 a 和 c 就變成了不同對象, 這是因?yàn)?Integer 的實(shí)現(xiàn)原理, /*** 使用 new(int x) 創(chuàng)建對象的時候, 如下, 會創(chuàng)建新對象:* public Integer(int value) {* this.value = value;* }* * Integer.valueOf(int x) 方法源碼如下, 如果 x 在 IntegerCache.low 和 IntegerCache.high * (-128~127)之間,會直接從 IntegerCache.cache[] 數(shù)組里面取, 也就是說是基本類型數(shù)值 x=9 ,而* 下面的128超出了這個范圍,會調(diào)用構(gòu)造器創(chuàng)建新對象 :* 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);}?
轉(zhuǎn)載于:https://my.oschina.net/wliming/blog/1512257
總結(jié)
以上是生活随笔為你收集整理的new Integer 和 Integer.valueOf 有什么不同的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ZigBee TI ZStack CC2
- 下一篇: Java注释用处