1. 程式人生 > 程式設計 >[Java原始碼]Integer

[Java原始碼]Integer

這次我們來看看Integer的原始碼,基於 jdk1.8.0_181.jdk 版本,如有錯誤,歡迎聯絡指出。

類定義

public final class Integer extends Number implements Comparable<Integer>
複製程式碼

帶有final標識,也就是說不可繼承的。另外繼承了Number類,而Number類實現了Serializable介面,所以Integer也是可以序列化的;實現了Comparable介面。

屬性

@Native public static final int   MIN_VALUE = 0x80000000;

@Native public
static final int MAX_VALUE = 0x7fffffff; 複製程式碼
  • MIN_VALUE 表示了Integer最小值,對應為-2^31
  • MAX_VALUE 表示了Integer最大值,對應為2^31 - 1

這裡的兩個常量都帶有@Native註解,表示這兩個常量值欄位可以被native程式碼引用。當native程式碼和Java程式碼都需要維護相同的變數時,如果Java程式碼使用了@Native標記常量欄位時,編譯時可以生成對應的native程式碼的標頭檔案。

@Native public static final int SIZE = 32;
複製程式碼

表示了Integer的bit數,32位。也使用了@Native註解,這裡有個比較有意思的問題,Why is the SIZE constant only @Native for Integer and Long? 可以進行深入閱讀瞭解。

public static final int BYTES = SIZE / Byte.SIZE;
複製程式碼

表示了Integer的位元組數,計算值固定為4

@SuppressWarnings("unchecked")
public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int"
); 複製程式碼

獲取類資訊,Integer.TYPE == int.class,兩者是等價的。

final static char[] digits = {
  '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
};
複製程式碼

代表了所有可能字元。因為允許二進位制至36進位制,所有必須有36個字元代表所有可能情況。

final static char [] DigitTens = {
  '0','0',} ;

final static char [] DigitOnes = {
  '0',} ;
複製程式碼

定義了兩個陣列,DigitTens存放了0~99之間的數字的十位數字符;DigitOnes存放了0~99之間的數字的個位數字元。

final static int [] sizeTable = { 9,99,999,9999,99999,999999,9999999,99999999,999999999,Integer.MAX_VALUE };
複製程式碼

陣列,存放了範圍各位數整數的最大值。

private final int value;
複製程式碼

Integerint的包裝類,這裡就是存放了int型別對應的資料值資訊

@Native private static final long serialVersionUID = 1360826667806852920L;
複製程式碼

內部類

private static class IntegerCache {
  static final int low = -128;
  static final int high;
  static final Integer cache[];

  static {
    // high value may be configured by property
    int h = 127;
    String integerCacheHighPropValue =
      sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
    if (integerCacheHighPropValue != null) {
      try {
        int i = parseInt(integerCacheHighPropValue);
        i = Math.max(i,127);
        // Maximum array size is Integer.MAX_VALUE
        h = Math.min(i,Integer.MAX_VALUE - (-low) -1);
      } catch( NumberFormatException nfe) {
        // If the property cannot be parsed into an int,ignore it.
      }
    }
    high = h;

    cache = new Integer[(high - low) + 1];
    int j = low;
    for(int k = 0; k < cache.length; k++)
      cache[k] = new Integer(j++);

    // range [-128,127] must be interned (JLS7 5.1.7)
    assert IntegerCache.high >= 127;
  }

  private IntegerCache() {}
}
複製程式碼

IntegerCacheInteger的靜態內部類,內部定義了一個陣列,用於快取常用的數值範圍,避免後續使用時重新例項化,提升效能。其預設快取的範圍是-128~127,我們可以通過-XX:AutoBoxCacheMax=<size>選項自行配置快取最大值,但是必須要大於等於127。

方法

構造方法

public Integer(int value) {
  this.value = value;
}

public Integer(String s) throws NumberFormatException {
  this.value = parseInt(s,10);
}
複製程式碼

存在兩個構造方法,一個引數為int型別,一個為String型別;引數為String物件時,內部呼叫了parseInt方法使用十進位制進行處理。

parseInt 方法

public static int parseInt(String s) throws NumberFormatException {
  return parseInt(s,10);
}

public static int parseInt(String s,int radix)
  throws NumberFormatException
    {
      /*
      * 注意:這個方法在VM初始化時可能會早於 IntegerCache 的初始化過程,所以值得注意的是不要使用 valueOf 方法 
      */
      
        // 判斷空值
        if (s == null) {
            throw new NumberFormatException("null");
        }
				
        // Character.MIN_RADIX = 2
        // 判斷最小進位制
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        // Character.MAX_RADIX = 36
        // 判斷最大進位制
        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        int result = 0;
        boolean negative = false;
        int i = 0,len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // 第一個字元可能是"+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // 不能單獨只存在 "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Character.digit 返回對應字元對應進位制的數字值,如果輸入進位制不在範圍內或者字元無效,返回-1                
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                // 判斷結果是否溢位
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                // 判斷增加當前位後的計算結果是否溢位
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                // 採用了負數的形式存放結果
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }
複製程式碼

存在兩個parseInt方法,第一個內部呼叫了第二個方法實現,所以具體來看看第二個方法的實現。相關的程式碼已經增加了註釋,不重複介紹了。這裡存在一個比較有意思的地方,程式碼邏輯上通過計算負數,然後結果判斷符號位的邏輯進行運算,這樣子可以避免正負邏輯分開處理。另外具體不採用正數邏輯應該是Integer.MIN_VALUE轉換成正數時會產生溢位,需要單獨處理。

parseUnsignedInt 方法

public static int parseUnsignedInt(String s) throws NumberFormatException {
  return parseUnsignedInt(s,10);
}

public static int parseUnsignedInt(String s,int radix)
  throws NumberFormatException {
  // null空值判斷
  if (s == null)  {
    throw new NumberFormatException("null");
  }

  int len = s.length();
  if (len > 0) {
    char firstChar = s.charAt(0);
    // 判斷第一個字元,無符號字串處理,出現了非法符號‘-’
    if (firstChar == '-') {
      throw new
        NumberFormatException(String.format("Illegal leading minus sign " +
                                            "on unsigned string %s.",s));
    } else {
      if (len <= 5 || // Integer.MAX_VALUE以36進位制形式表示為6位字元
          (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE以十進位製表示為10位字元
        // 這個範圍內,完全確保在int的數值範圍
        return parseInt(s,radix);
      } else {
        long ell = Long.parseLong(s,radix);
        // 判斷是不是超過32bit的範圍
        if ((ell & 0xffff_ffff_0000_0000L) == 0) {
          return (int) ell;
        } else {
          throw new
            NumberFormatException(String.format("String value %s exceeds " +
                                                "range of unsigned int.",s));
        }
      }
    }
  } else {
    throw NumberFormatException.forInputString(s);
  }
}
複製程式碼

存在兩個parseUnsignedInt方法,第一個方法內部呼叫了第二個方法實現。我們來看看第二個方法,首先判斷字串是否符合格式要求;然後判斷範圍,在int範圍內的使用parseInt處理,否則使用Long.parseLong處理,再強制轉成int資料型別返回對應結果。

getChars 方法

static void getChars(int i,int index,char[] buf) {
  int q,r;
  int charPos = index;
  char sign = 0;

  // 不支援Integer.MIN_VALUE,轉換成正數時會產生溢位
  if (i < 0) {
    sign = '-';
    i = -i;
  }

  // 每次迴圈,處理兩位數字
  // 從低位開始,所以索引是在向前走,從後往前
  while (i >= 65536) {
    q = i / 100;
    // 相當於 r = i - (q * 100);
    r = i - ((q << 6) + (q << 5) + (q << 2));
    i = q;
    buf [--charPos] = DigitOnes[r];
    buf [--charPos] = DigitTens[r];
  }

  // 對於小於等於 65536 的數字,採用快速下降模式
  // assert(i <= 65536,i);
  for (;;) {
    q = (i * 52429) >>> (16+3);
    // 相當於 r = i - (q * 10)
    r = i - ((q << 3) + (q << 1));
    buf [--charPos] = digits [r];
    i = q;
    if (i == 0) break;
  }
  if (sign != 0) {
    buf [--charPos] = sign;
  }
}
複製程式碼

該方法主要的邏輯就是將輸入int型別資料轉換成字元形式放入char陣列中,不支援 Integer.MIN_VALUE

當輸入值大於65536時,每次處理兩位數字,進行效率的提升;另外中間乘法操作也都使用位移運算來替代。

這裡比較有意思的是當數字小於等於65536時的計算邏輯,中間計算使用了52429這個數字,那麼為什麼是它呢?這裡說一下我的看法,僅個人觀點,如有錯誤歡迎指出。先看下程式碼的註釋資訊:

// I use the "invariant division by multiplication" trick to

// accelerate Integer.toString. In particular we want to

// avoid division by 10.

//

// The "trick" has roughly the same performance characteristics

// as the "classic" Integer.toString code on a non-JIT VM.

// The trick avoids .rem and .div calls but has a longer code

// path and is thus dominated by dispatch overhead. In the

// JIT case the dispatch overhead doesn't exist and the

// "trick" is considerably faster than the classic code.

//

// TODO-FIXME: convert (x * 52429) into the equiv shift-add

// sequence.

//

// RE: Division by Invariant Integers using Multiplication

// T Gralund,P Montgomery

// ACM PLDI 1994

//

  1. 52429 / 2^(16+3) = 0.10000038146972656,實際這裡的操作就是除以10的邏輯。
  2. 主要是使用乘法和移位操作來代替除法操作,提升效能。具體原理說明可以參考論文 Division by Invariant Integers using Multiplication
  3. 這裡為什麼選擇65536作為界限說實話自己也沒有看明白,各處都沒有看到相關的說明。如果你瞭解,歡迎評論指出。
  4. 我們要確保乘法操作之後不能溢位,因為上面邏輯中i已經進行負數判斷,所有i必定為正數,我們可以認為乘積是個無符號整數,最大值為2^32(後續的無符號右移可以對應);也就是對應的乘數必須小於 2^32 / 65536,即65536。
  5. (i * 52429) >>> (16+3);其中52429為乘數,設為a,16+3為指數,設為b。也就是a / (2^b) = 0.1,即a = 2^b / 10。但是呢這樣可能會由於除數向下取整,導致結果錯誤的問題,舉個例子:
System.out.println((1120 * 52428) >>> (16+3)); // 111
System.out.println((1120 * 52429) >>> (16+3)); // 112
複製程式碼

所以進行修正,改成a = 2^b / 10 + 1,避免向下取整可能帶來的問題

  1. 然後進行多組資料測試
乘數: 2,指數:4,除法: 2 / 16.0 = 0.125
乘數: 4,指數:5,除法: 4 / 32.0 = 0.125
乘數: 7,指數:6,除法: 7 / 64.0 = 0.109375
乘數: 13,指數:7,除法: 13 / 128.0 = 0.1015625
乘數: 26,指數:8,除法: 26 / 256.0 = 0.1015625
乘數: 52,指數:9,除法: 52 / 512.0 = 0.1015625
乘數: 103,指數:10,除法: 103 / 1024.0 = 0.1005859375
乘數: 205,指數:11,除法: 205 / 2048.0 = 0.10009765625
乘數: 410,指數:12,除法: 410 / 4096.0 = 0.10009765625
乘數: 820,指數:13,除法: 820 / 8192.0 = 0.10009765625
乘數: 1639,指數:14,除法: 1639 / 16384.0 = 0.10003662109375
乘數: 3277,指數:15,除法: 3277 / 32768.0 = 0.100006103515625
乘數: 6554,指數:16,除法: 6554 / 65536.0 = 0.100006103515625
乘數: 13108,指數:17,除法: 13108 / 131072.0 = 0.100006103515625
乘數: 26215,指數:18,除法: 26215 / 262144.0 = 0.10000228881835938
乘數: 52429,指數:19,除法: 52429 / 524288.0 = 0.10000038146972656
乘數: 104858,指數:20,除法: 104858 / 1048576.0 = 0.10000038146972656
乘數: 209716,指數:21,除法: 209716 / 2097152.0 = 0.10000038146972656
乘數: 419431,指數:22,除法: 419431 / 4194304.0 = 0.10000014305114746
複製程式碼

可以看出來,52429是這個範圍內精度最大的值,所以選擇這個值。另外從結果看當指數大於19時,精度的提升已經很小,所以猜測可能選定了這個指數後確定了65536的範圍,當然也只是猜測。

上面的說明大致介紹了程式碼邏輯,但這也是出於時代的原因(當時的機器裝置效能等),從jdk9的原始碼來看,這裡的程式碼已經進行了重構,改成了簡單易理解的除法操作。具體的這裡有個對應的issue,從目前現狀來看兩者的效能差距幾乎可以忽略不計吧。

stringSize 方法

static int stringSize(int x) {
  for (int i=0; ; i++)
    if (x <= sizeTable[i])
      return i+1;
}
複製程式碼

獲取對應資料的字串長度,通過sizeTable去遍歷查詢;從邏輯可以看出,只支援正數,負數的結果是錯誤的。

toString 方法

public static String toString(int i) {
  if (i == Integer.MIN_VALUE)
    return "-2147483648";
  int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
  char[] buf = new char[size];
  getChars(i,size,buf);
  return new String(buf,true);
}
複製程式碼

輸入int資料型別的引數,對於Integer.MIN_VALUE進行了特殊判斷,相等就返回固定字串"-2147483648",這裡的邏輯是因為後續的getChars方法不支援Integer.MIN_VALUE。判斷正負數,負數的陣列大小比正數多1,用於存放-符號。最後呼叫的String的構造方法,返回結果字串。

public String toString() {
  return toString(value);
}
複製程式碼

直接呼叫了上面的toString方法進行處理

public static String toString(int i,int radix) {
  // 判斷進位制範圍,不在範圍內,預設設為十進位制
  if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
    radix = 10;

  // 如果是十進位制,呼叫上面的toString方法返回結果
  if (radix == 10) {
    return toString(i);
  }

  char buf[] = new char[33];
  boolean negative = (i < 0);
  int charPos = 32;

  // 正數轉換成負數,統一後續處理邏輯
  if (!negative) {
    i = -i;
  }

  while (i <= -radix) {
    buf[charPos--] = digits[-(i % radix)];
    i = i / radix;
  }
  buf[charPos] = digits[-i];

  if (negative) {
    buf[--charPos] = '-';
  }

  return new String(buf,charPos,(33 - charPos));
}
複製程式碼

這個方法帶了進位制資訊,若進位制不在設定範圍內,預設使用十進位制進行處理。然後轉換成對應的字串,程式碼邏輯比較簡單。

toUnsignedLong 方法

public static long toUnsignedLong(int x) {
  return ((long) x) & 0xffffffffL;
}
複製程式碼

轉換成無符號的long型別資料,保留低32位bit資料,高32位設為0。0和正數等於其自身,負數等於輸入加上2^32。

divideUnsigned 方法

public static int divideUnsigned(int dividend,int divisor) {
  // In lieu of tricky code,for now just use long arithmetic.
  return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
}
複製程式碼

轉換成無符號long型別資料相除,返回無符號整數結果。

remainderUnsigned 方法

public static int remainderUnsigned(int dividend,for now just use long arithmetic.
  return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
}
複製程式碼

轉換成無符號long型別資料,進行取餘操作,返回無符號整數結果。

numberOfLeadingZeros 方法

public static int numberOfLeadingZeros(int i) {
  // HD,Figure 5-6
  if (i == 0)
    return 32;
  int n = 1;
  if (i >>> 16 == 0) { n += 16; i <<= 16; }
  if (i >>> 24 == 0) { n +=  8; i <<=  8; }
  if (i >>> 28 == 0) { n +=  4; i <<=  4; }
  if (i >>> 30 == 0) { n +=  2; i <<=  2; }
  n -= i >>> 31;
  return n;
}

// 類似二分查詢的思想,通過左右移位縮小1所在bit位置的範圍。舉個例子看下
// 開始輸入          i = 00000000 00000000 00000000 00000001      n = 1
// i >>> 16 == 0,  i = 00000000 00000001 00000000 00000000      n = 17
// i >>> 24 == 0,  i = 00000001 00000000 00000000 00000000      n = 25
// i >>> 28 == 0,i = 00010000 00000000 00000000 00000000      n = 29
// i >>> 30 == 0,i = 01000000 00000000 00000000 00000000      n = 31
// n = n - i >>> 31,i >>> 31 = 0,所以n = 31
複製程式碼

判斷二進位制格式下,最高位的1左邊存在多少個0。這裡使用了二分查詢的思想,通過左右移位的操作一步步縮小1所在的bit位置範圍,最後通過簡單計算獲取0的個數。開始增加了對特殊值0的判斷。

numberOfTrailingZeros 方法

public static int numberOfTrailingZeros(int i) {
  // HD,Figure 5-14
  int y;
  if (i == 0) return 32;
  int n = 31;
  y = i <<16; if (y != 0) { n = n -16; i = y; }
  y = i << 8; if (y != 0) { n = n - 8; i = y; }
  y = i << 4; if (y != 0) { n = n - 4; i = y; }
  y = i << 2; if (y != 0) { n = n - 2; i = y; }
  return n - ((i << 1) >>> 31);
}

// 類似二分查詢的思想,通過左移縮小0所在bit位置的範圍。舉個例子看下
// 開始輸入          i = 11111111 11111111 11111111 11111111    n = 31
// i << 16 != 0,   i = 11111111 11111111 00000000 00000000    n = 15
// i << 8 != 0,    i = 11111111 00000000 00000000 00000000    n = 7
// i << 4 != 0,i = 11110000 00000000 00000000 00000000    n = 3
// i << 2 != 0,i = 11000000 00000000 00000000 00000000    n = 1
// (i << 1) >>> 31 => 00000000 00000000 00000000 00000001 => 1
// 結果為 1 - 1 = 0
複製程式碼

與上面的numberOfLeadingZeros方法對應,獲取二進位制格式下尾部的0的個數。具體邏輯與上面類似,就不再贅述了。

formatUnsignedInt 方法

/**
* 將無符號整數轉換成字元陣列
* @param val 無符號整數
* @param shift 基於log2計算, (4 對應十六進位制,3 對應八進位制,1 對應二進位制)
* @param buf 字元寫入陣列
* @param offset 陣列起始位置偏移量
* @param len 字元長度
* @return 字元寫入陣列後對應的起始位置
*/
static int formatUnsignedInt(int val,int shift,char[] buf,int offset,int len) {
  int charPos = len;
  int radix = 1 << shift;
  int mask = radix - 1;
  do {
    // val & mask,獲取最後一位數字值
    buf[offset + --charPos] = Integer.digits[val & mask];
		
    // 移位去除最後一位數字,類似於十進位制除10邏輯
    val >>>= shift;
  } while (val != 0 && charPos > 0);

  return charPos;
}
複製程式碼

將無符號整數轉換成字串寫入對應的陣列位置,返回寫入陣列後的起始位置。

toUnsignedString 方法

public static String toUnsignedString(int i,int radix) {
    return Long.toUnsignedString(toUnsignedLong(i),radix);
}
複製程式碼

將輸入整數按進位制轉換成無符號的字串,內部呼叫了toUnsignedLong獲取無符號的long型別資料,然後轉換成對應的字串。

toXxxString 方法

public static String toHexString(int i) {
  return toUnsignedString0(i,4);
}

public static String toOctalString(int i) {
  return toUnsignedString0(i,3);
}

public static String toBinaryString(int i) {
  return toUnsignedString0(i,1);
}

private static String toUnsignedString0(int val,int shift) {
  // assert shift > 0 && shift <=5 : "Illegal shift value";
  int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
  int chars = Math.max(((mag + (shift - 1)) / shift),1);
  char[] buf = new char[chars];

  // 呼叫formatUnsignedInt,獲取對應字串陣列資訊
  formatUnsignedInt(val,shift,buf,0,chars);

  // Use special constructor which takes over "buf".
  return new String(buf,true);
}
複製程式碼

toHexString,toOctalString,toBinaryString三個方法如名字一樣獲取不同進位制的字串,內部呼叫了toUnsignedString0方法進行處理,傳入了不用的進位制數引數。

valueOf 方法

public static Integer valueOf(String s) throws NumberFormatException {
  return Integer.valueOf(parseInt(s,10));
}

public static Integer valueOf(String s,int radix) throws NumberFormatException {
  return Integer.valueOf(parseInt(s,radix));
}

public static Integer valueOf(int i) {
  if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
  return new Integer(i);
}
複製程式碼

存在三個valueOf方法,主要看看第三個方法。當引數在快取範圍內時,直接從快取陣列中獲取對應的Integer物件;超出範圍時,例項化對應的引數物件返回結果。

xxxValue 方法

public byte byteValue() {
  return (byte)value;
}

public short shortValue() {
  return (short)value;
}

public int intValue() {
  return value;
}

public long longValue() {
  return (long)value;
}

public float floatValue() {
  return (float)value;
}

public double doubleValue() {
  return (double)value;
}
複製程式碼

直接進行強制型別轉換,返回對應的結果

hashCode

@Override
public int hashCode() {
  return Integer.hashCode(value);
}

public static int hashCode(int value) {
  return value;
}
複製程式碼

對應的值作為其hashCode。

equals 方法

public boolean equals(Object obj) {
  if (obj instanceof Integer) {
    return value == ((Integer)obj).intValue();
  }
  return false;
}
複製程式碼

判斷obj是不是Integer的例項物件,然後判斷兩者的值是否相等。這裡可以看出來,我們可以不需要對obj進行null判斷。

decode 方法

public static Integer decode(String nm) throws NumberFormatException {
  int radix = 10;
  int index = 0;
  boolean negative = false;
  Integer result;

  if (nm.length() == 0)
    throw new NumberFormatException("Zero length string");
  char firstChar = nm.charAt(0);
  // 判斷負數
  if (firstChar == '-') {
    negative = true;
    index++;
  } else if (firstChar == '+')
    index++;

  // 判斷十六進位制
  if (nm.startsWith("0x",index) || nm.startsWith("0X",index)) {
    index += 2;
    radix = 16;
  }
  // 判斷十六進位制
  else if (nm.startsWith("#",index)) {
    index ++;
    radix = 16;
  }
  // 判斷八進位制
  else if (nm.startsWith("0",index) && nm.length() > 1 + index) {
    index ++;
    radix = 8;
  }
	
  // 字串格式不合法
  if (nm.startsWith("-",index) || nm.startsWith("+",index))
    throw new NumberFormatException("Sign character in wrong position");

  try {
    // 如果是 Integer.MIN_VALUE,轉換成正數會溢位丟擲異常
    result = Integer.valueOf(nm.substring(index),radix);
    result = negative ? Integer.valueOf(-result.intValue()) : result;
  } catch (NumberFormatException e) {
    // 處理 數字是 Integer.MIN_VALUE的異常錯誤資訊,如果存在錯誤,會繼續丟擲異常
    String constant = negative ? ("-" + nm.substring(index))
      : nm.substring(index);
    result = Integer.valueOf(constant,radix);
  }
  return result;
}
複製程式碼

將對應的字串轉換成整數,支援十進位制,0x,0X,#開頭的十六進位制數,0開頭的八進位制數。

getInteger 方法

// 返回對應數值或者null
public static Integer getInteger(String nm) {
  return getInteger(nm,null);
}

// 返回對應的數值或者val預設值
public static Integer getInteger(String nm,int val) {
  Integer result = getInteger(nm,null);
  return (result == null) ? Integer.valueOf(val) : result;
}

public static Integer getInteger(String nm,Integer val) {
  String v = null;
  try {
    // 獲取對應的系統配置資訊
    v = System.getProperty(nm);
  } catch (IllegalArgumentException | NullPointerException e) {
  }
  if (v != null) {
    try {
      return Integer.decode(v);
    } catch (NumberFormatException e) {
    }
  }
  return val;
}
複製程式碼

三個getInteger方法,主要是最後一個方法。傳入一個配置的key以及預設值,獲取對應的系統配置值,若為空或者為null,返回對應的預設值。

compare 方法

public static int compare(int x,int y) {
  return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
複製程式碼

比較兩個整數,x < y 返回-1,x == y 返回0,x > y 返回1

compareTo 方法

public int compareTo(Integer anotherInteger) {
  return compare(this.value,anotherInteger.value);
}
複製程式碼

內部呼叫compare方法實現具體邏輯

compareUnsigned 方法

public static int compareUnsigned(int x,int y) {
  return compare(x + MIN_VALUE,y + MIN_VALUE);
}
複製程式碼

兩個輸入數當作無符號整數進行比較,這裡通過加上MIN_VALUE確保在範圍內。有個小技巧,-1加上MIN_VALUE後會變成最大正數。

System.out.println((-1 + Integer.MIN_VALUE) == Integer.MAX_VALUE); // true
複製程式碼

highestOneBit 方法

public static int highestOneBit(int i) {
  // HD,Figure 3-1
  i |= (i >>  1);
  i |= (i >>  2);
  i |= (i >>  4);
  i |= (i >>  8);
  i |= (i >> 16);
  return i - (i >>> 1);
}

// 移位或邏輯,保證1+2+4+8+16=31位最後都為1,相減最後保留最高位1
// 輸入              00010000 00000000 00000000 00000001
// i |= (i >>  1)   00011000 00000000 00000000 00000000
// i |= (i >>  2)   00011110 00000000 00000000 00000000
// i |= (i >>  4)   00011111 11100000 00000000 00000000
// i |= (i >>  8)   00011111 11111111 11100000 00000000
// i |= (i >> 16)   00011111 11111111 11111111 11111111
// i - (i >>> 1)    00010000 00000000 00000000 00000000
複製程式碼

獲取最高位為1,其餘為0的整數值。通過位移或邏輯,將最高位右邊1位設為1,然後2倍增長左移或操作,1的位數不斷增加,最後1+2+4+8+16=31,可以確保覆蓋所有可能性。然後使用i - (i >>> 1)保留最高位1返回結果。

lowestOneBit 方法

public static int lowestOneBit(int i) {
  // HD,Section 2-1
  return i & -i;
}

// 輸入 00000000 00000000 00000000 11101010
// -i  11111111 11111111 11111111 00010110
// 結果 00000000 00000000 00000000 00000010
複製程式碼

獲取最低位1,其餘位為0的值。負數以正數的補碼錶示,對整數的二進位制進行取反碼然後加1,得到的結果與輸入二進位制進行與操作,結果就是最低位1保留,其他位為0。

bitCount 方法

public static int bitCount(int i) {
  // HD,Figure 5-2
  i = i - ((i >>> 1) & 0x55555555);
  i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
  i = (i + (i >>> 4)) & 0x0f0f0f0f;
  i = i + (i >>> 8);
  i = i + (i >>> 16);
  return i & 0x3f;
}
複製程式碼

統計二進位制格式下1的數量。程式碼第一眼看著是懵的,都是位運算,實際裡面實現的演演算法邏輯還是很巧妙的,著實佩服,這裡就不介紹了,感興趣的可以看下別人的具體分析文章 java原始碼Integer.bitCount演演算法解析,分析原理(統計二進位制bit位)這篇文章,我覺得已經說得很清晰了。

rotateXXX 方法

public static int rotateLeft(int i,int distance) {
  return (i << distance) | (i >>> -distance);
}

public static int rotateRight(int i,int distance) {
  return (i >>> distance) | (i << -distance);
}
複製程式碼

旋轉二進位制,rotateLeft將特定位數的高位bit放置低位,返回對應的數值;rotateRight將特定位數的低位bit放置高位,返回對應的數值。當distance是負數的時候,rotateLeft(val,-distance) == rotateRight(val,distance)以及rotateRight(val,-distance) == rotateLeft(val,distance)。另外,當distance是32的任意倍數時,實際是沒有效果的 ,相當於無操作。

這裡需要說一下(i >>> -distance)diatance為正數時,右移一個負數邏輯相當於i >>> 32+(-distance)

reverse 方法

public static int reverse(int i) {
  // HD,Figure 7-1
  i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
  i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
  i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
  i = (i << 24) | ((i & 0xff00) << 8) |
    ((i >>> 8) & 0xff00) | (i >>> 24);
  return i;
}
複製程式碼

看著是不是和bitCount有點類似,其實核心邏輯相似。先是交換相鄰1位bit的順序,然後再交換相鄰2位bit順序,再繼續交換相鄰4位bit順序,這樣子每一個byte內的bit流順序已經翻轉過來了,然後採用和reverseBytes一樣的邏輯,將對應bit位按位元組為單位翻轉,這樣子就完成了所有bit的翻轉操作,甚是絕妙。

signum 方法

public static int signum(int i) {
  // HD,Section 2-7
  return (i >> 31) | (-i >>> 31);
}

// 輸入 1      00000000 00000000 00000000 00000001
// i >> 31    00000000 00000000 00000000 00000000
// -i         11111111 11111111 11111111 11111111
// -i >>> 31  00000000 00000000 00000000 00000001
// 結果返回1
複製程式碼

獲取符號數,若為負數,返回-1;若為0則返回0;為正數,則返回1。

reverseBytes 方法

public static int reverseBytes(int i) {
  return ((i >>> 24)           ) |
    ((i >>   8) &   0xFF00) |
    ((i <<   8) & 0xFF0000) |
    ((i << 24));
}
複製程式碼

按照輸入引數二進位制格式,以位元組為單位翻轉,返回對應的結果數值。(i >>> 24) | (i << 24)交換最高8位和最低8位bit位置。((i >> 8) & 0xFF00) | ((i << 8) & 0xFF0000)為交換中間16位bit位置的邏輯。

sum、max、min方法

public static int sum(int a,int b) {
  return a + b;
}

public static int max(int a,int b) {
  return Math.max(a,b);
}

public static int min(int a,int b) {
  return Math.min(a,b);
}
複製程式碼

這個就不說了,很簡單的方法。

總結

由於存在很多的位運算邏輯,第一眼感覺程式碼邏輯是比較複雜的,但是當慢慢品味時,發現程式碼思路甚是奇妙,演演算法之神奇,只能拍手稱讚?。為了效能,所做的各種小優化也是體現其中,不過部分這個比較hack的值設定缺乏完整的註釋理解也是比較困難。總而言之,只能感慨程式碼實現之奇妙。

最後

部落格原文地址:blog.renyijiu.com/post/java原始碼…