比較物件實質內容值要使用equals(),別使用 == 或 != (== 或 != 是比較物件參考或參考物件名稱 Integer c1)
Java 並非完全的物件導向程式語言,要區別 Primitive Type 與 Class Type 的不同。
我們沒什麼不同
當你宣告一個基本型態變數並指定值時,例如:
int x = 1;
JVM會在記憶體的stack區開設一塊空間,儲存1這個值
當你宣告一個參考名稱,並建立一個物件指定給該名稱時,例如:
Object o = new Object();
使用new時,JVM會在heap區取得一個空間來建立物件,你將物件指定給參考名稱,表示你將物件的記憶體位址設定給參考名稱,也就是JVM會在stack開設一塊空間,儲存這個記憶體位址
Java中的參考與C++中的參考指的並不是相同的東西
實際上,Java 建構式是有傳回值的,傳回值就是物件在記憶體中的位址,只不過你不能處理這個位址資訊罷了。
物件指定性與相等性
IntegerDemo
C:\workspace\IntegerDemo
<4-15, Java SE7>
Integer i1 = 100;
Integer i2 = 100;
if(i1 == i2)
System.out.println("i1 == i2");
else
System.out.println("i1 != i2");
以上為i == i2,當i1,i2都為200時,結果為 i1 != i2。
以上值在-128~127之間,i1 與 i2 會參考到同一個 Integer 實例。
java\lang\Integer.java
private static class IntegerCache {
static final int low = -128;
static final int high;
...
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
以上 IntegerCache.low 預設值-128,執行期間無法更改。
IntegerCache.high 預設值127,可以於啟動JVM時以 java.lang.Integer.IntegerCache.high來指定。
<4-15, Java SE7>
Integer i1 = 100;
Integer i2 = 100;
if(i1 == i2)
System.out.println("i1 == i2");
else
System.out.println("i1 != i2");
以上為i == i2,當i1,i2都為200時,結果為 i1 != i2。
以上值在-128~127之間,i1 與 i2 會參考到同一個 Integer 實例。
java\lang\Integer.java
private static class IntegerCache {
static final int low = -128;
static final int high;
...
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
以上 IntegerCache.low 預設值-128,執行期間無法更改。
IntegerCache.high 預設值127,可以於啟動JVM時以 java.lang.Integer.IntegerCache.high來指定。