標籤:源碼 對象 編譯器 緩衝 坑
其實,java在自動裝箱和自動拆箱的過程裡面,留了不少的坑給我們,我們下面將以integer這個類為基礎討論一下
其實這裡面主要涉及的是兩點
1.當使用Integer x=1,這樣的方式來賦值的時候,其實,編譯器當那個1是String,然後需要通過valueof的方法轉換過來,但是在轉換的過程中,他為了最佳化速度,使用了我們所不知道的緩衝,因為在這裡會出現一些坑
2.Integer類裡面重寫了equals方法,裡面不但對比對象,而且還對比裡面的值
下面先上代碼:(請仔細觀看注釋,裡面已經提供了上面所述兩個方法的源碼)
package com.ray.object;/** * 自動裝箱與自動拆箱的坑 * * @author ray * @since 2015-05-04 * @version 1.0 * */public class Test {public static void main(String[] args) {// 其實下面這幾句後面的賦值1,1,1000,1000,都被當做是string,// 然後通過Integer.valueOf()這個方法轉換過來,// 我們下面來看看Integer.valueOf()這個方法的源碼// public static Integer valueOf(int i) {// if(i >= -128 && i <= IntegerCache.high)// return IntegerCache.cache[i + 128];// else// return new Integer(i);// }// 在源碼裡面其實是緩衝了一部分資料,是-128-127// 因此,在a==b是返回true// c==d是返回falseInteger a = 1;Integer b = 1;Integer c = 1000;Integer d = 1000;System.out.println("a == b ---- " + (a == b));// trueSystem.out.println("c == d ---- " + (c == d));// false// 這下面是構造4個integer的對象出來Integer a_1 = new Integer(1);Integer b_1 = new Integer(1);Integer c_1 = new Integer(1000);Integer d_1 = new Integer(1000);// 下面兩句是通過==對比對象,當然是false了System.out.println("a_1 == b_1 ---- " + (a_1 == b_1));// falseSystem.out.println("c_1 == d_1 ---- " + (c_1 == d_1));// false// 下面兩句是通過equals對比對象,integer類裡面重寫了equals方法// 看看重寫後equals方法的代碼// public boolean equals(Object obj) {// if (obj instanceof Integer) {// return value == ((Integer)obj).intValue();// }// return false;// }// 我們可以看到出來對比對象之外,還對比本身的值,所以返回trueSystem.out.println("a_1.equals(b_1) ---- " + a_1.equals(b_1));// trueSystem.out.println("c_1.equals(d_1) ---- " + c_1.equals(d_1));// true}}
輸出:
a == b ---- true
c == d ---- false
a_1 == b_1 ---- false
c_1 == d_1 ---- false
a_1.equals(b_1) ---- true
c_1.equals(d_1) ---- true
java-基礎入門-自動裝箱與自動拆箱留給我們的坑