package com.test;
public class 解包裝包 {
public static void main(String []args) {
Integer a = 100;
Integer b = 100;
System.out.println(a==b);
}
}
打印結果為:true
但是如果換成 128 > var >= -128 之外的整數(shù)就打false了。
這是什么原因呢?
1。java在編譯的時候 Integer a = 100; 被翻譯成-> Integer a = Integer.valueOf(100);
2。比較的時候仍然是對象的比較
3。在jdk源碼中
。。。
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
。。。
而
。。。
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache = new Integer(i - 128);
}
}
。。。
這邊是java為了提高效率,初始化了-128--127之間的整數(shù)對象
所以在賦值在這個范圍內(nèi)都是同一個對象。
再加一句
Integer a = 100;
a++;
//這邊a++是新創(chuàng)建了一個對象,不是以前的對象。
public static void main(String []args) {
Integer a = 100;
Integer b = a;
a++;
System.out.println(a==b);
}
打印就是false
對于127--128沒有多大關系,但是在這范圍之外就影響性能了吧,就像StringBuffer VS String一樣了
public class 解包裝包 {
public static void main(String []args) {
Integer a = 100;
Integer b = 100;
System.out.println(a==b);
}
}
打印結果為:true
但是如果換成 128 > var >= -128 之外的整數(shù)就打false了。
這是什么原因呢?
1。java在編譯的時候 Integer a = 100; 被翻譯成-> Integer a = Integer.valueOf(100);
2。比較的時候仍然是對象的比較
3。在jdk源碼中
。。。
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
。。。
而
。。。
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache = new Integer(i - 128);
}
}
。。。
這邊是java為了提高效率,初始化了-128--127之間的整數(shù)對象
所以在賦值在這個范圍內(nèi)都是同一個對象。
再加一句
Integer a = 100;
a++;
//這邊a++是新創(chuàng)建了一個對象,不是以前的對象。
public static void main(String []args) {
Integer a = 100;
Integer b = a;
a++;
System.out.println(a==b);
}
打印就是false
對于127--128沒有多大關系,但是在這范圍之外就影響性能了吧,就像StringBuffer VS String一樣了
</script>