//person.age爲Integer類型
if(2 == person.age) {
//如果person.age == null的話,會報空指針
// 因爲它會將 person.age拆箱成基本數據類型int,然後調用intValue()方法,自然就會報空指針了
}
// 拆箱時調用的方法
public int intValue() {
return value;
}
// 裝箱時調用的方法
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
/**
:返回表示指定{@code INT}值的{@code整數}實例。 如果不需要新的{@code整數}例如,這種方法一般應優先使
用構造{@link#整數(INT)},因爲此方法可能通過緩存經常產生顯著更好的空間和時間性能 請求的值。
**這種方法將在範圍內始終緩存值-128到127,包容性,並可以外接高速緩存的這個範圍以外的值**。 @Param
我的{@code INT}值。
返回:表示{@code I} {一個整數@code}實例。 @since 1.5
*/
//對於-128到127之間的數,會進行緩存,Integer i6 = 127時,會將127進行緩存,下次再寫Integer i7 = 127
//時,就會直接從緩存中取,就不會new了。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Ingeter是int的包裝類,int的初值爲0,Ingeter的初值爲null。
無論如何,Integer與new Integer()不會相等。不會經歷拆箱過程,i8的引用指向堆,而i4指向專門存放他的內存(常量池),他們的內存地址不一樣,使用 == 比較都爲false。
兩個都是非new出來的Integer,使用 == 比較,如果數在-128到127之間,則是true,否則爲false
兩個都是new出來的,==比較都爲false。若要比較值是否相等,需使用equals方法進行比較。
int和Integer(無論new否)比,都爲true,因爲會把Integer自動拆箱爲int再去比。
Integer a1 = 127;
Integer a2 = 127;
System.out.println(a1 == a2);// true
System.out.println(a1.equals(a2));// true
System.out.println("==========================");
Integer b1 = 128;
Integer b2 = 128;
System.out.println(b1 == b2);// false
System.out.println(b1.equals(b2));// true
System.out.println("==========================");
Integer c1 = 128;
int c2 = 128;
System.out.println(c1 == c2);// true
System.out.println(c1.equals(c2));// true
System.out.println("==========================");
int d1 = 127;
Integer d2 = null;
System.out.println(d1 == d2);// NullPointerException
System.out.println("==========================");
int e1 = 128;
Integer e2 = 128;
Integer e3 = new Integer(128);
System.out.println(e1 == e2); ////true
System.out.println(e2 == e3); //false
System.out.println(new Integer(e1).equals(e2)); //true
System.out.println("==========================");
Integer f1 = 127;
Integer f2 = new Integer(127);
System.out.println(f1 == f2); //false
System.out.println(f1.equals(f2)); //true