[Java源碼]Integer

此次咱們來看看Integer的源代碼,基於 jdk1.8.0_181.jdk 版本,若有錯誤,歡迎聯繫指出。java

類定義

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

帶有final標識,也就是說不可繼承的。另外繼承了Number類,而Number類實現了Serializable接口,因此Integer也是能夠序列化的;實現了Comparable接口。git

屬性

@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? 能夠進行深刻閱讀了解。segmentfault

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個字符表明全部可能狀況。less

final static char [] DigitTens = {
  '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
  '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
  '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
  '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
  '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
  '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
  '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
  '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
  '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
  '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
} ;

final static char [] DigitOnes = {
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
} ;
複製代碼

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

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

數組,存放了範圍各位數整數的最大值。ide

private final int value;
複製代碼

Integerint的包裝類,這裏就是存放了int類型對應的數據值信息post

@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, int divisor) {
  // In lieu of tricky code, 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源碼…

相關文章
相關標籤/搜索