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