探索JDK

探索JDK之Integer类

2018-10-24  本文已影响0人  苏小小北

1. 简介

Integer类封装了一个值int原始类型的一个对象。一个Integer类型的对象包含一个字段的类型是int。此外,该类提供了一些方法处理int、String的相关的操作。

2. 源码


Integer类中属性有:

(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对象,具体见静态内部类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,基数自动从字符串解析, 用于解析系统属性参数
    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):从系统属性解析读取指定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. 从系统属性解析读取指定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 左边全变为 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):补码对应前缀连续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):补码对应后缀连续0的个
    同25中 numberOfLeadingZeros(int i)的前缀连续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的个数
    这是比较巧妙一种方式,详解见https://www.jianshu.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):二进制按位反转
    非常巧妙一种方式,详解见https://www.jianshu.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):按字节反转
    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) 静态内部类:
  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() {}
    }

其他


本人也是在慢慢学习中,如有错误还请原谅、敬请指出,谢谢!

上一篇下一篇

猜你喜欢

热点阅读