Class前的註釋就不翻譯了,對源碼的設計說明有限。直接上代碼:
- 先看一下它的繼承、實現關係:
public final class Integer extends Number implements Comparable<Integer>
- Number是個抽象類,大概包含六個抽象方法,都是用來類型轉換的 具體代碼如下:
這就是繼承後 子類的實現,強轉。public abstract class Number implements java.io.Serializable { public abstract int intValue(); public abstract long longValue(); public abstract float floatValue(); public abstract double doubleValue(); public byte byteValue() { return (byte)intValue(); } public short shortValue() { return (short)intValue(); } /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -8742448824652078965L; }
public long longValue() { return (long)value; }
- 看下Comparable 接口,只有一個compareTo 比較大小方法:
看下Integer的具體public int compareTo(T o);
如果看代碼有點費勁,那複製如下代碼,自己運行下看結果就懂了。public int compareTo(Integer anotherInteger) { return compare(this.value, anotherInteger.value); } public static int compare(int x, int y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); }
public class Test { public static void main(String[] args) { Integer it1=128; Integer it2=-128; Integer it3=128; System.out.println(it2.compareTo(it1)+"-----x < y"); System.out.println(it1.compareTo(it2)+"------x > y"); System.out.println(Integer.compare(it1,it3)+"-----x == y"); } }
打印結果:-1-----x < y 1------x > y 0-----x == y
2. Integer的緩存問題
Integer默認放入緩存的區間是-128 至127 。但最大緩存值可以手動調整,請看:
The Javadoc comment clearly states that this class is for cache and to support the autoboxing of values between 128 and 127. The high value of 127 can be modified by using a VM argument -XX:AutoBoxCacheMax=size
. So the caching happens in the for-loop. It just runs from the low to high and creates as many Integer instances and stores in an Integer array named cache. As simple as that. This caching is doing at the first usage of the Integer class. Henceforth, these cached instances are used instead of creating a new instance (during autoboxing).
public class IntegerTest {
public static void main(String[] args) {
Integer it1=2008;
Integer it2=2008;
System.out.println(it1==it2);//true 說明:爲啥超了127了還是true呢?因爲我設置了vm arguments參數 -XX:AutoBoxCacheMax=2008
Integer it1t=2009;
Integer it2t=2009;
System.out.println(it1t==it2t);//false 說明:超過 2008 false了吧~~
Integer newit1=new Integer(127);
Integer newit2=new Integer(127);
System.out.println(newit1==newit2);//false 說明:New的話是在heap上佔用獨立內存的新對象
int it3=127;
int it4=127;
int it5=2008;
System.out.println(it3==it4);//true
System.out.println(it1==it5);//true
}
}
print result :true
false
false
true
true
設置虛擬機啓動參數
凌晨了,有時間再記~睡覺。