Integer类有一个缓存,会缓存介于-128~127之间的整数
public class Test {
public static void main(String[] args) {
Integer i1 = 127;
Integer i2 = 127;
System.err.println(i1 == i2);
i1 = 128;
i2 = 128;
System.err.println(i1 == i2);
System.err.println(i1.hashCode() == i2.hashCode());
}
}
true
false
true
Integer.valueOf(int i) 优先取缓存的Integer,而不采用构造方法。如手动采用构造方法,则不采用缓存。
,会缓存介于-128~127之间的整数。
.当数值不在-128~127时,无论通过哪种方式,即使两个对象的值相等,通过“==”比较,其结果为false;
Integer重写了hashCode方法,返回值是value,即Integer对象 的数值。