1. 程式人生 > 其它 >8 種基本型別的包裝類和常量池

8 種基本型別的包裝類和常量池

Java 基本型別的包裝類的大部分都實現了常量池技術

Byte,Short,Integer,Long這 4 種包裝類預設建立了數值[-128,127]的相應型別的快取資料,Character建立了數值在[0,127]範圍的快取資料,Boolean直接返回TrueOrFalse

兩種浮點數型別的包裝類Float,Double並沒有實現常量池技術。

Integer i1 = 33;
Integer i2 = 33;
System.out.println(i1 == i2);// 輸出 true
Integer i11 = 333;
Integer i22 = 333;
System.out.println(i11 
== i22);// 輸出 false Double i3 = 1.2; Double i4 = 1.2; System.out.println(i3 == i4);// 輸出 false

Integer 快取原始碼:

/**
*此方法將始終快取-128 到 127(包括端點)範圍內的值,並可以快取此範圍之外的其他值。
*/
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
      return IntegerCache.cache[i 
+ (-IntegerCache.low)]; return new Integer(i); } private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; }

Character快取原始碼:

public static Character valueOf(char c) {
    if (c <= 127) { // must cache
      return CharacterCache
.cache[(int)c]; } return new Character(c); } private static class CharacterCache { private CharacterCache(){} static final Character cache[] = new Character[127 + 1]; static { for (int i = 0; i < cache.length; i++) cache[i] = new Character((char)i); } }

Boolean快取原始碼:

public static Boolean valueOf(boolean b) {
    return (b ? TRUE : FALSE);
}

如果超出對應範圍仍然會去建立新的物件,快取的範圍區間的大小隻是在效能和資源之間的權衡。

下面我們來看一下問題。下面的程式碼的輸出結果是true還是flase呢?

Integer i1 = 40;
Integer i2 = new Integer(40);
System.out.println(i1==i2);

Integer i1=40這一行程式碼會發生拆箱,也就是說這行程式碼等價於Integer i1=Integer.valueOf(40)。因此,i1直接使用的是常量池中的物件。而Integer i1 = new Integer(40)會直接建立新的物件。

此,答案是false。你答對了嗎?

記住:所有整型包裝類物件之間值的比較,全部使用 equals 方法比較。

Integer 比較更豐富的一個例子:

Integer i1 = 40;
Integer i2 = 40;
Integer i3 = 0;
Integer i4 = new Integer(40);
Integer i5 = new Integer(40);
Integer i6 = new Integer(0);

System.out.println(i1 == i2);// true
System.out.println(i1 == i2 + i3);//true
System.out.println(i1 == i4);// false
System.out.println(i4 == i5);// false
System.out.println(i4 == i5 + i6);// true
System.out.println(40 == i5 + i6);// true

i1,i2,i3都是常量池中的物件,i4,i5,i6是堆中的物件。

i4 == i5 + i6為什麼是 true 呢?因為,i5i6會進行自動拆箱操作,進行數值相加,即i4 == 40

Integer物件無法與數值進行直接比較,所以i4自動拆箱轉為 int 值 40,最終這條語句轉為40 == 40進行數值比較