1. 程式人生 > >10.1java原始碼解析-Integer (1)

10.1java原始碼解析-Integer (1)

1類的宣告

public final class Integer extends Number implements Comparable<Integer>
  • 繼承 Number
  • 實現 Comparable<Integer> 可以比較大小

2類屬性

  @Native public static final int   MIN_VALUE = 0x80000000;
  @Native public static final int   MAX_VALUE = 0x7fffffff;
  @Native public static final int SIZE = 32;

  public static final int BYTES = SIZE / Byte.SIZE;
    

3建構函式

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

  
  public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
    }

下面會對 parseInt(s, 10);進行詳細說明

4方法

4.1toString(int i, int radix)

 public static String toString(int i, int radix) {
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        /* Use the faster version */
        if (radix == 10) {/*--------1*/
            return toString(i);
        }

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

        if (!negative) {
            i = -i;
        }

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

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

        return new String(buf, charPos, (33 - charPos));
    }

  • 1處的意思是如果是十進位制就直接返回字串
  • 2處33字元陣列是因為 進位制最小是2進位制,而整型的2進位制是32位,再加上1一個符號位,所以就33個字元。
  • 3處 進行進位制處理
  • 4 新增符號

4.2toUnsignedString

獲取整型的補碼以 radix顯示

 public static String toUnsignedString(int i, int radix) {
        return Long.toUnsignedString(toUnsignedLong(i), radix);
    }
    

補碼標註

  • 正數的補碼還是原碼
  • 負數的補碼是原碼取反加1。

4.3 進位制轉化

 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);/*-----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]; /*-----2*/

        formatUnsignedInt(val, shift, buf, 0, chars);/*-----3*/

        // Use special constructor which takes over "buf".
        return new String(buf, true);
    }
    
 static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
        int charPos = len;
        int radix = 1 << shift;/*-----4*/
        int mask = radix - 1;
        do {
            buf[offset + --charPos] = Integer.digits[val & mask];/*-----5*/
            val >>>= shift;/*-----6*/
        } while (val != 0 && charPos > 0);

        return charPos;
    }

通過原碼可以看出,轉化進位制呼叫的是同一個方法,只是引數不一樣

  • 1呼叫相同方法
  • 2通過上面程式碼操作,可以獲得最後轉化為進位制補碼的字串長度,從而減少不必要的記憶體消耗
  • 3 呼叫求補碼的方法,引數
  • val 原值
  • shift 1代表2進位制,2代表4進位制,3代表8進位制,4代表16進位制
  • buf 代表轉化完的進位制字串儲存處。
  • offset 開始位置
  • len 長度
  • 4 將傳的 1,2,3,4 轉化為進位制數 2,4,8,16
  • 5 將值與進位制數進行與運算,類似於 取餘操作,例如 例如20的2進製表示為 10100,10100&1111 =100 這就會獲得最後四位的2進位制碼。
  • 6進行移位,把剛才處理過的位去掉。10100移位就是 1,然後再重複5操作,便會得到 14,而20的16進位制就是14。 通俗解釋

就是每 shift位數轉化為進位制數,也就是上問中的 1,2,3,4

4.4 toString(int i)

這個方法本來不想寫的,但看了原始碼,發現很多疑惑,分享一下

 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'
	    };
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',
        } ;
 public static String toString(int i) {
        if (i == Integer.MIN_VALUE)
            return "-2147483648";
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);/*-----1*/
        char[] buf = new char[size];
        getChars(i, size, buf);
        return new String(buf);
    }
static void getChars(int i, int index, char[] buf) {
    int q, r;
    int charPos = index;
    char sign = 0;

    if (i < 0) {
        sign = '-';
        i = -i;
    }

    // Generate two digits per iteration
    while (i >= 65536) {
        q = i / 100;
    // really: r = i - (q * 100);
        r = i - ((q << 6) + (q << 5) + (q << 2));
        i = q;
        buf [--charPos] = DigitOnes[r];
        buf [--charPos] = DigitTens[r];
    }

    // Fall thru to fast mode for smaller numbers
    // assert(i <= 65536, i);
    for (;;) {
        q = (i * 52429) >>> (16+3);/*-----2*/
        r = i - ((q << 3) + (q << 1));  // r = i-(q*10) .../*-----3*/
        buf [--charPos] = digits [r]; /*-----4*/
        i = q;
        if (i == 0) break;
    }
    if (sign != 0) {
        buf [--charPos] = sign;
    }
}

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

// Requires positive x
static int stringSize(int x) {
    for (int i=0; ; i++)
        if (x <= sizeTable[i])
            return i+1;
}

  • 想不到吧,tostring方法竟然這麼麻煩,我的疑惑是,上面既然已經有toString(int i,int j)的方法,為什麼不直接呼叫,為什麼tostring不直接 return ""+i; 呢
  • 具體解釋如下
  • 1 處的意思是 獲取 數的位數,如,12 的位數是2,2343的位數是4,檢視stringSize可知,是通過呼叫靜態陣列列表來獲取的。
  • 2 處的意思是 個人理解,就是獲取最低位前所有位的數,例如,123獲取的就是12,1245獲取的就是124
  • 3處的意思是 就是獲取最末位的數字
  • 4 處的意思是根據數字大小來獲取字串中位置的值,並插入到char陣列中

4.5parseInt

 public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */

        if (s == null) {
            throw new NumberFormatException("null");
        }

        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        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') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                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;
    }

    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }
  • 其實就是把字串拆解,然後每個char 都進行 Character.digit(s.charAt(i++),radix);解析,然後再拼接成整型
  • 這裡有一個問題 ,按理說 parseInt(String s,int i),i應該表示的是進位制,但是,心在只有輸入10是對的,其他值都會異常

4.6parseUnsignedInt(String s, int radix)

 public static int parseUnsignedInt(String s, int radix)
                throws NumberFormatException {
        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 in Character.MAX_RADIX is 6 digits
                    (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
                    return parseInt(s, radix);
                } else {
                    long ell = Long.parseLong(s, radix);
                    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);
        }
    }