Java會自動進行拆箱裝箱,是以int和Integer的比較是值,值相等永遠相等。(Integer和int比較時,Integer會自動拆箱)
如果是兩個Integer比較,這絕對不相等,因為比較的是兩個對象,記憶體位址都不一樣。
Integer和int比較時,Integer可能為空的情況下:
String.valueOf(foldeType).equals(x.getFoldeType())
空指針異常
Integer a = null;
System.out.println(a==2);
錯誤提示:
Exception in thread "main" java.lang.NullPointerException
at imooccache.ImoocCache1.main(ImoocCache1.java:37)
在-128到127的範圍裡會利用IntegerCache緩存。
Integer b = 1026;
Integer c = 1026;
System.out.println(b==c);//false
Integer b = -128;
Integer c = -128;
System.out.println(b==c);//true
Integer b = 127;
Integer c = 127;
System.out.println(b==c);//true
對象裡的age是int
public static void main(String[] args) {
int a =1026;
Integer b = 1026;
Man man = new Man(1026);
System.out.println(man.getAge() == a);//true
System.out.println(man.getAge() == b);//true
System.out.println(a == b);//true
}
static class Man {
private int age;
public Man(Integer age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
對象裡的age是Integer
public static void main(String[] args) {
int a =1026;
Integer b = 1026;
Man man = new Man(1026);
System.out.println(man.getAge() == a);//true
System.out.println(man.getAge() == b);//false
System.out.println(a == b);//true
}
static class Man {
private Integer age;
public Man(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
再例如:
public static void main(String[] args) {
int a =1026;
Integer b = 1026;
int c = 1026;
Integer d = 1026;
System.out.println(a == b);//true
System.out.println(a == c);//true
System.out.println(a == d);//true
System.out.println(b == c);//true
System.out.println(b == d);//false
System.out.println(c == d);//true
}
Integer的緩存區源碼:
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}