1. 继承关系
Integer继承自抽象类Number,实现了Comparable<>接口.
2. IntegerCache内部类
他还有一个IntegerCache内部类,里面存了-128到127的Integer对象;
当我们用int数据给Integer型对象引用赋值时,采用自动装箱的办法,调用valueOf()方法;
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
可以看到,如果int型值在-128至127之间时,直接返回的cache中的对象;如果不在这个范围则直接返回一个新的对象。也就是说,对于在[-128,127]内的数,无论它赋给了多少个对象引用,这些引用都指向的同一个对象。因此对于
Integer i1, i2, i3, i4;
i1 = 100;
i2 = 100;
i3 = 100;
i4 = 100;
它们四个是完全相同的,都指向同一个对象,即使用==
判断,返回的是true
;而对于
Integer i1, i2, i3, i4;
i1 = 1000;
i2 = 1000;
i3 = 1000;
i4 = 1000;
它们四个只是值相等,但是是不同的对象,使用==
判断,返回的false
,若要只比较值,则使用i1.equals(i2)
。
3. hashCode()方法
public static int hashCode(int value) {
return value;
}
可以看到,它的hash值就是它自己。