探索JDK之Integer類

1. 簡介

Integer類封裝了一個值int原始類型的一個對象。一個Integer類型的對象包含一個字段的類型是int。此外,該類提供了一些方法處理int、String的相關的操作脱惰。

2. 源碼


Integer類中屬性有:

  • 實例變量
  • 實例方法
  • 類變量
  • 類方法
  • 靜態(tài)內部類
  • 構造器
(1) 實例變量:
  1. value:表示數值大小(final不可變)
    private final int value;
(2) 實例方法:
  1. byteValue:返回截斷的byte類型值
    public byte byteValue() {
        return (byte)value;
    }
  1. shortValue:返回截斷的short類型值
    public short shortValue() {
        return (short)value;
    }
  1. intValue:返回int類型值
    public int intValue() {
        return value;
    }
  1. longValue:返回long類型值
    public long longValue() {
        return (long)value;
    }
  1. floatValue:返回float類型值
    public float floatValue() {
        return (float)value;
    }
  1. doubleValue:返回double類型值
    public double doubleValue() {
        return (double)value;
    }
  1. toString: 重寫Object類的toString方法窿春,這里調用了類方法toString拉一,后面解釋
    public String toString() {
        return toString(value);
    }
  1. hashCode:返回hash值,實際上類方法hashCode也只是返回value旧乞, 所以說蔚润,Integer的hash值就是數值value
    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }
  1. equals:與其他對象比較大小(可以跟任何對象比較)
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
  1. compareTo:與另一Integer比較大小
    public int compareTo(Integer anotherInteger) {
        return compare(this.value, anotherInteger.value);
    }
(3) 類變量:
  1. MIN_VALUE:Integer最小值尺栖,為-21473648
    public static final int   MIN_VALUE = 0x80000000;
  1. MAX_VALUE:Integer最大值嫡纠,為21473647
    public static final int   MAX_VALUE = 0x7fffffff;
  1. TYPE:對應的原始類的類型"int"
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
  1. digits:每一個數字大小的對應字符表示
    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'
    };
  1. DigitTens:0-99的十位上數字矩陣
    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',
        } ;
  1. DigitOnes:0-99的個位上數字矩陣
    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',
        } ;
  1. sizeTable:輔助數組
    final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
                                      99999999, 999999999, Integer.MAX_VALUE };
  1. SIZE:Integer數值二進制占用bit數目,為32
    public static final int SIZE = 32;
  1. BYTES:Integer數值二進制占用byte數目延赌, 為4
    public static final int BYTES = SIZE / Byte.SIZE;
  1. serialVersionUID:序列版本號
    private static final long serialVersionUID = 1360826667806852920L;
(4) 類方法:
  1. toString(int i):返回數值為i的字符串除盏,基數為10
    public static String toString(int i) {
        if (i == Integer.MIN_VALUE)
            return "-2147483648";
        //stringSize根據i的大小來判斷
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        // getChars 下見詳解
        getChars(i, size, buf);
        // 返回buf數組的String
        return new String(buf, true);
    }
    static void getChars(int i, int index, char[] buf) {
        int q, r;
        int charPos = index;
        char sign = 0;

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

        // 每兩位的來取,并且這里的取余用位移來代替了
        // r = i % 100 等價于
        // r = i - (q * 100) 等價于 
        // r = i - (q * 64 + q * 32 + q * 4) 等價于
        // r = i - ((q << 6) + (q << 5) + (q << 2))
        while (i >= 65536) {
            q = i / 100;
            r = i - ((q << 6) + (q << 5) + (q << 2));
            i = q;
            buf [--charPos] = DigitOnes[r];
            buf [--charPos] = DigitTens[r];
        }

        // i <= 65536挫以,這里每次取一位
        // 對10進行取余同上者蠕,但是這里取商也采用一個中特殊方式
        // q = (i * 52429) >>> (16+3); 推導如下
        // 2 >>> 19 為 524288,
        // q = (i * 52429) / 524288 = (i * 52428.8 + i * 0.2) >>> (16+3)掐松,
        // i * 0.2 最大值為13107.2 踱侣,i 拆分為兩部分粪小,i = a * 10 + b(保證0<=b<=9)
        // q = ((a*10+b) * 52428.8 + i * 0.2) >>> 19
        // q = (a * 524288 + 52428.8 * b + i * 0.2)  >>> 19
        // 52428.8 * b 最大值為52428.8 * 9, i * 0.2 最大值為 13107.2
        // 所以 52428.8 * b + i * 0.2 最大值為 484966.4, 小于 524288 = 1 >>> 19, 對應二進制會被右移掉
        // 所以 q = (a * 524288) >>> 19 + (52428.8 * b + i * 0.2) >>>19 = (a*524288) >>> 524288 = a
        // assert(i <= 65536, i);
        for (;;) {
            q = (i * 52429) >>> (16+3);
            r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
            buf [--charPos] = digits [r];
            i = q;
            if (i == 0) break;
        }
        if (sign != 0) {
            buf [--charPos] = sign;
        }
    }
  1. toString(int i, int radix):返回數值為i的字符串抡句,基數為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) {
            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));
    }
  1. toUnsignedString0(int val, int shift):將integer轉換為無符號數的字符串形式
    /**
     *  將int值轉換為字符串形式糕再,基數為 1 << shift
     * @param val 要轉換的值
     * @param shift 基數偏移量,1 對應基數為 2(1 << 1). 3 對應基數為 8(1 << 2)
     * @return 字符串玉转,基數為 1 << shift
     */
    private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        // numberOfLeadingZeros 源碼在下,計算補碼的前綴0的個數
        // 以偏移來計算非0前綴數字的字符串殴蹄,基數為 1 << shift
        int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
        int chars = Math.max(((mag + (shift - 1)) / shift), 1);
        char[] buf = new char[chars];

        formatUnsignedInt(val, shift, buf, 0, chars);

        // Use special constructor which takes over "buf".
        return new String(buf, true);
    }
    
    /**
     * 
     * @param i 輸入int值
     * @return 返回對應二進制補碼的前綴0的個數究抓,負數補碼以1開頭,故全為0
     */
    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;
    }
    /**
     * Format a long (treated as unsigned) into a character buffer.
     * @param val the unsigned int to format
     * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
     * @param buf the character buffer to write to
     * @param offset the offset in the destination buffer to start at
     * @param len the number of characters to write
     * @return the lowest character  location used
     */
     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];
            // 利用偏移來代替除法運算袭灯,這也就是不直接用radix做方法參數的原因
            val >>>= shift;
        } while (val != 0 && charPos > 0);

        return charPos;
    }
  1. toBinaryString(int i):轉換為二進制形式(補碼)
    看懂3中的toUnsignedString0方法刺下,這個應該就比較簡單
    // 直接調用toUnsingedString0方法,radix為2稽荧,所以shift為1
    public static String toBinaryString(int i) {
        return toUnsignedString0(i, 1);
    }
  1. toOctalString(int i):轉換為八進制形式(補碼)
    看懂3中的toUnsignedString0方法橘茉,這個應該就比較簡單
    // 直接調用toUnsignedString0方法,radix為8姨丈, 所以shift為3
    public static String toOctalString(int i) {
        return toUnsignedString0(i, 1);
    }
  1. toHexString(int i):轉換為十六進制形式(補碼)
    看懂3中的toUnsignedString0方法畅卓,這個應該就比較簡單
    // 直接調用toUnsignedString0方法,radix為16蟋恬, 所以shift為4
    public static String toHexString(int i) {
        return toUnsignedString0(i, 4);
    }
  1. toUnsignedLong(int x):轉換為long 無符號類型
    public static long toUnsignedLong(int x) {
        return ((long) x) & 0xffffffffL;//將(long)x 的補碼與32位全1 取與
    }
  1. toUnsignedString(int i):轉換為long無符號字符串
    public static String toUnsignedString(int i) {
        return Long.toString(toUnsignedLong(i));
    }
  1. parseInt(String s, int radix):將String解析成int翁潘,基數為radix
    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");
        }
        // radix 不能小于2
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }
        // radix不能大于32
        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
                // Character.digit(char ch, int radix) 將字符轉換為數值歼争,基數為radix
                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;
    }
  1. parseInt(String s):將String解析成int拜马,基數為10
    // 直接調用9中的方法parseInt(s, 10)
    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }
  1. parseUnsignedInt(String s, int radix):將無符號類型數值的String轉換為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.parseLong(char ch, int radix)沐绒,返回對應的long值
                    long ell = Long.parseLong(s, radix);
                    if ((ell & 0xffff_ffff_0000_0000L) == 0) {
                        // 保證無符號類型的數值不會超過 2**32(4294967296)
                        return (int) ell;
                    } else {
                        throw new
                            NumberFormatException(String.format("String value %s exceeds " +
                                                                "range of unsigned int.", s));
                    }
                }
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
    }

  1. parseUnsingedInt(String s): 將無符號類型數值的String轉換為int俩莽,基數為10
    // 直接調用11中的parseUnsignedInt(String s, int radix)
    public static int parseUnsignedInt(String s) throws NumberFormatException {
        return parseUnsignedInt(s, 10);
    }
  1. valueOf(String s, int radix):同11中 parseInt(char ch, int radix)
    public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return Integer.valueOf(parseInt(s,radix));
    }
  1. valueOf(String s):同12中 parseInt(char ch)
    public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }
  1. valueOf(int i):根據int值返回Integer對象,如果在緩存池中乔遮,會返回緩存池中的對象扮超,否則new對象,返回對象蹋肮。緩存池默認是緩存 -128 ~ 127 的Interger對象瞒津,具體見靜態(tài)內部類IntegerCache。
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
  1. hashCode():hash值括尸,返回value巷蚪,每一個相等大小的Integer對象的hash值都相等
    public static int hashCode(int value) {
        return value;
    }
  1. decode(String nm):解析字符串為Integer,基數自動從字符串解析濒翻, 用于解析系統(tǒng)屬性參數
    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);
        // Handle sign, if present
        if (firstChar == '-') {
            negative = true;
            index++;
        } else if (firstChar == '+')
            index++;

        // Handle radix specifier, if present
        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 {
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? Integer.valueOf(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            // If number is Integer.MIN_VALUE, we'll end up here. The next line
            // handles this case, and causes any genuine format error to be
            // rethrown.
            String constant = negative ? ("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }
        return result;
    }
  1. getInteger(String nm, Integer val):從系統(tǒng)屬性解析讀取指定key的屬性值v屁柏,失敗返回默認val對象
    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;
    }
  1. 從系統(tǒng)屬性解析讀取指定key的屬性值v啦膜,失敗返回默認值為val的Integer
    public static Integer getInteger(String nm, int val) {
        Integer result = getInteger(nm, null);
        return (result == null) ? Integer.valueOf(val) : result;
    }
  1. compare(int x, int y):比較大小
    public static int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }
  1. compareUnsigned(int x, int y):比較無符號int的值大小
    // 如果x,y 均為正數淌喻,誰值大僧家,對應的無符號值也大
    // 如果x,y 均為負數裸删,誰值更小八拱,加上MIN_VALUE越界更多,所以值越大
    // 如果x涯塔,y 一正一負肌稻,負數+MIN_VALUE越界為正數,所以肯定負數大
    public static int compareUnsigned(int x, int y) {
        return compare(x + MIN_VALUE, y + MIN_VALUE);
    }
  1. divideUnsigned(int dividend, int divisor) :無符號int數值相除
    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));
    }
  1. remainderUnsigned(int dividend, int divisor):無符號int數值取余
    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));
    }
  1. highestOneBit(int i):取數值對應二進制的最高位第一個1匕荸,然后其他位全設為0爹谭,返回這個值
    例如:0000 0000 1110 0011 0000 1001 0011 0011
    返回:0000 0000 1000 0000 0000 0000 0000 0000

    // 通常我們獲取最高位1用 去一位一位的找 的方法去做,這樣遍歷32次才可以
    // 這里是將最高位1 左邊全變?yōu)?1榛搔,然后 減去 右移一位的 值诺凡,即可得到我們想要值
    // 例如 0000 0000 1110 0011 0000 1001 0011 0011
    // 轉換為 0000 0000 1111 1111 1111 1111 1111 1111
    // 再減去 0000 0000 0111 1111 1111 1111 1111 1111
    // 得到 0000 0000 1000 0000 0000 0000 0000 0000

    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. lowestOneBit(int i):取數值對應二進制的最低位第一個1,然后其他全設為0践惑,返回這個值
    例如:0000 0000 1110 0011 0000 1001 0011 0000
    返回:0000 0000 0000 0000 0000 0000 0001 0000

    // 通常我們獲取最高位1用 去一位一位的找 的方法去做,這樣遍歷32次才可以
    // 這里運用了位與運算尔觉,一種很巧妙的方式
    // 例如
    // 正數原碼為 0000 0000 1110 0011 0000 1001 0011 0000
    // 相反數原碼為 0000 0000 1110 0011 0000 1001 0011 0000
    // 相反數反碼為 1111 1111 0001 1100 1111 0110 1100 1111
    // 此時 正數原碼 與 相反數反碼 正好完全相反真屯,取&為0
    // 相反數補碼為 1111 1111 0001 1100 1111 0110 1101 0000
    // 相反數補碼 + 1 后,所影響的數字從最后一位向高傳播穷娱,終止條件碰到第一0(反碼的0绑蔫,正數原碼對應的是1)
    // 所以,得到 0000 0000 0000 0000 0000 0000 0001 0000

    public static int lowestOneBit(int i) {
        // HD, Section 2-1
        return i & -i;
    }
  1. numberOfLeadingZeros(int i):補碼對應前綴連續(xù)0的個數
    // 前綴0的個數泵额,也就是找到最高位1的位置
    // 通常我們獲取最高位1用 去一位一位的找 的方法去做配深,這樣遍歷32次才可以
    // 這里運用了二分的方式去搜索,log(N)內完成
    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. numberOfTrailingZeros(int i):補碼對應后綴連續(xù)0的個
    同25中 numberOfLeadingZeros(int i)的前綴連續(xù)0的個數求法
    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);
    }
  1. bitCount(int i):計算二進制中1的個數
    這是比較巧妙一種方式嫁盲,詳解見http://www.reibang.com/p/0d0439dc7c6d
    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. rotateLeft(int i, int distance):二進制按位左旋轉
    public static int rotateLeft(int i, int distance) {
        return (i << distance) | (i >>> -distance);
    }
  1. rotateRight(int i, int distance):二進制按位右旋轉
    public static int rotateRight(int i, int distance) {
        return (i >>> distance) | (i << -distance);
    }
  1. reverse(int i):二進制按位反轉
    非常巧妙一種方式篓叶,詳解見http://www.reibang.com/u/0e206eac3b5c
    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;
    }
  1. signum(int i):正負號函數
    ???為什么要判斷-i>>>31
    public static int signum(int i) {
        // HD, Section 2-7
        return (i >> 31) | (-i >>> 31);
    }
  1. reverseBytes(int i):按字節(jié)反轉
    public static int reverseBytes(int i) {
        return ((i >>> 24)           ) |
               ((i >>   8) &   0xFF00) |
               ((i <<   8) & 0xFF0000) |
               ((i << 24));
    }
  1. sum(int a, int b):求和
    public static int sum(int a, int b) {
        return a + b;
    }
  1. max(int a, int b):取最大值
    public static int max(int a, int b) {
        return Math.max(a, b);
    }
  1. min(int a, int b):取最小值
    public static int min(int a, int b) {
        return Math.min(a, b);
    }
(5) 構造器:
  1. Integer(int value):按int構造
    public Integer(int value) {
        this.value = value;
    }
  1. Integer(String s):按String構造
    public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
    }
(6) 靜態(tài)內部類:
  1. IntegerCache:Integer緩存池
    這也是為什么值相同的Integer對象a和Integer b, a == b 有時返回true羞秤,有時返回false的原因
    緩存的值下限:low = -128缸托,不可修改
    緩存的值上限:high,未設置瘾蛋,默認是127俐镐,但可以通過java.lang.Integer.IntegerCache.high屬性設置其他值。
    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() {}
    }

其他


本人也是在慢慢學習中哺哼,如有錯誤還請原諒佩抹、敬請指出叼风,謝謝!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末棍苹,一起剝皮案震驚了整個濱河市无宿,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌枢里,老刑警劉巖孽鸡,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件描验,死亡現(xiàn)場離奇詭異侧蘸,居然都是意外死亡,警方通過查閱死者的電腦和手機备埃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門冰悠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人配乱,你說我怎么就攤上這事溉卓。” “怎么了搬泥?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵桑寨,是天一觀的道長。 經常有香客問我忿檩,道長尉尾,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任燥透,我火速辦了婚禮沙咏,結果婚禮上,老公的妹妹穿的比我還像新娘班套。我一直安慰自己肢藐,他們只是感情好,可當我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布吱韭。 她就那樣靜靜地躺著吆豹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪理盆。 梳的紋絲不亂的頭發(fā)上痘煤,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天,我揣著相機與錄音猿规,去河邊找鬼衷快。 笑死,一個胖子當著我的面吹牛姨俩,可吹牛的內容都是我干的烦磁。 我是一名探鬼主播养匈,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼都伪!你這毒婦竟也來了呕乎?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤陨晶,失蹤者是張志新(化名)和其女友劉穎猬仁,沒想到半個月后,有當地人在樹林里發(fā)現(xiàn)了一具尸體先誉,經...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡湿刽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了褐耳。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片诈闺。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖铃芦,靈堂內的尸體忽然破棺而出雅镊,到底是詐尸還是另有隱情,我是刑警寧澤刃滓,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布仁烹,位于F島的核電站,受9級特大地震影響咧虎,放射性物質發(fā)生泄漏卓缰。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一砰诵、第九天 我趴在偏房一處隱蔽的房頂上張望征唬。 院中可真熱鬧,春花似錦茁彭、人聲如沸鳍鸵。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽偿乖。三九已至,卻和暖如春哲嘲,著一層夾襖步出監(jiān)牢的瞬間贪薪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工眠副, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留画切,地道東北人。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓囱怕,卻偏偏與公主長得像霍弹,于是被迫代替她去往敵國和親毫别。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內容

  • Java源碼 Integer Integer的簽名如下典格,繼承了Number類并實現(xiàn)Comparable接口 Com...
    wngn123閱讀 1,247評論 0 2
  • 1.編譯程序(1)gcc xx.c,他會默認生成一個a.out的可執(zhí)行文件岛宦,在a.out所在目錄,執(zhí)行./a.o...
    萌面大叔2閱讀 1,290評論 0 1
  • 一耍缴、Java 簡介 Java是由Sun Microsystems公司于1995年5月推出的Java面向對象程序設計...
    子非魚_t_閱讀 4,195評論 1 44
  • Integer類為java基本類型int的包裝類砾肺,除了前面提到的Byte類,Short類中的大部分方法防嗡,Integ...
    Kinsanity閱讀 909評論 0 2
  • 1 關鍵字 1.1 關鍵字的概述 Java的關鍵字對java的編譯器有特殊的意義变汪,他們用來表示一種數據類型,或...
    哈哈哎呦喂閱讀 655評論 0 0