• Java中Integer的源码学习


     
    一、开始
    public final class Integer extends Number implements Comparable<Integer>
    
    1)、由于类修饰符中有关键字final,故该类不能够被继承
    2)、继承了抽象类Number
    3)、实现了接口Comparable,即实现了compareTo方法
    4)、重写了hashCode和equals方法,其中hashCode是value,而equals只是比较同种类型的intValue的值
    
    
        public int compareTo(Integer anotherInteger) {
            return compare(this.value, anotherInteger.value);
        }
    
        public static int compare(int x, int y) {
            return (x < y) ? -1 : ((x == y) ? 0 : 1);
        }
    
        public int hashCode() {
            return value;
        }
    
        public boolean equals(Object obj) {
            //只有同种类型的才能进行判断是否相等
            if (obj instanceof Integer) {
                return value == ((Integer)obj).intValue();
            }
            return false;
        }

    二、parseInt将字符串数字转换为数值int

    //没有指定进制的,默认为10进制的字符串
    public static int parseInt(String s) throws NumberFormatException {
            return parseInt(s,10);
        }
       //radix是字符串s对应的进制
    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; } //如"1234567"就是-(((((((0*10-1)*10-2)*10-3)*10-4)*10-5)*10-6)*10-7) } else { throw NumberFormatException.forInputString(s); } return negative ? result : -result; }

    三、valueOf将字符串转换为数值Integer

     //来自于java.lang.Integer
         public static Integer valueOf(String s, int radix) throws NumberFormatException {
            return Integer.valueOf(parseInt(s,radix));
        }
    
        //同上
        public static Integer valueOf(String s) throws NumberFormatException {
            return Integer.valueOf(parseInt(s, 10));
        }
    
        //同上
        //只缓存[-128,127]
        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) {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low));
                }
                high = h;
    
                cache = new Integer[(high - low) + 1];
                int j = low;
                for(int k = 0; k < cache.length; k++)
                    cache[k] = new Integer(j++);
            }
    
            private IntegerCache() {}
        }
    
        //同上
        //当Integer num = 100;时,编译器会将其转化为Integer num = Integer.valueOf(100);
        public static Integer valueOf(int i) {
            assert IntegerCache.high >= 127;
            //当其在缓存范围内,则从缓存中获取,当不在时,则新建一个Integer对象
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
    
        //以下一些判断,通过上述学习就好理解了
        Integer num1 = Integer.valueOf(100);
        Integer num2 = Integer.valuefOf(100);
        Integer num3 = Integer.valueOf(200);
        Integer num4 = Integer.valuefOf(200);
        System.out.println(num1 == num2);//true
        System.out.println(num3 == num4);//false


    四、toString(i,radix)

    将整数转化为radix进制表示的字符串

        
        //来自于java.lang.Integer
        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'
        };
    
        //同上
        public static String toString(int i, int radix) {
    
            //当转换的进制不是在[2,36]之间,则按10进制进行转换
            //其中 public static final int MIN_RADIX = 2;
            //     public static final int MAX_RADIX = 36;
            if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
                radix = 10;
    
            /* Use the faster version */
            if (radix == 10) {
                //当是10进制转换时,
                return toString(i);
            }
    
            //存放转换后的字符数组
            char buf[] = new char[33];
            //判断是否是负数
            boolean negative = (i < 0);
            int charPos = 32;
    
            if (!negative) {
                //当不是负数,将其转为负数,这里是为了防止数据溢出
                //若不这么做,当其是负数时,将负数转变为正数,则会发生数据溢出,毕竟int的数据范围是[-2^31, 2^31-1],当Integer.MIN_VALUE=-2^31转化为正数时,绝对会溢出,防止,若是将Integer.MAX_VALUE=2^31-1转化为负数,就肯定没有数据溢出了。
                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));
        }
    
    
    
        //来自于java.lang.String.java
        public String(char value[], int offset, int count) {
            if (offset < 0) {
                throw new StringIndexOutOfBoundsException(offset);
            }
            if (count < 0) {
                throw new StringIndexOutOfBoundsException(count);
            }
            // Note: offset or count might be near -1>>>1.
            if (offset > value.length - count) {
                throw new StringIndexOutOfBoundsException(offset + count);
            }
            this.value = Arrays.copyOfRange(value, offset, offset+count);
        }
    
        //来自于java.util.Arrays.java
        public static char[] copyOfRange(char[] original, int from, int to) {
            int newLength = to - from;
            if (newLength < 0)
                throw new IllegalArgumentException(from + " > " + to);
            //根据长度新建一个字符数组,之后使用System.arraycopy进行数组拷贝
            char[] copy = new char[newLength];
            System.arraycopy(original, from, copy, 0,
                             Math.min(original.length - from, newLength));
            return copy;
        }

    五、toString(i)

    将整数i表示为10进制的字符串

        
        //来自于java.lang.Integer
        public static String toString(int i) {
            //当是最小值时,不适合使用以下方法,因为会发生数据溢出(在调用stringSize时),故直接返回
            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);
        }
    
        //同上
        static void getChars(int i, int index, char[] buf) {
            int q, r;
            int charPos = index;
            char sign = 0;
    
            if (i < 0) {
                //当是负数时,需要加上标记,以利于后期在字符数组中添加上
                sign = '-';
                i = -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;
                //获取其对10的余数,即 r%10
                buf [--charPos] = DigitOnes[r];
                //获取其对10的商,即 r/10
                buf [--charPos] = DigitTens[r];
            }
    
            // Fall thru to fast mode for smaller numbers
            // 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;
            }
        }
    
        //同上
        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;
        }
    
        //同上
        //100以内的数除以10所得到的商
        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',
        } ;
    
        //同上
        //100以内的数对10取余所得的余数
        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',
        } ;

      

     六、toHexString(i) toOctalString(i) toBinaryString(i)

    将整数转化为对应的进制字符串表示

        
        //来自于java.lang.Integer
           public static String toHexString(int i) {
            return toUnsignedString(i, 4);
        }
    
        //同上
        public static String toOctalString(int i) {
            return toUnsignedString(i, 3);
        }
    
        //同上
        public static String toBinaryString(int i) {
            return toUnsignedString(i, 1);
        }
    
        //同上
        private static String toUnsignedString(int i, int shift) {
            char[] buf = new char[32];
            int charPos = 32;
            int radix = 1 << shift;
            int mask = radix - 1;
            do {
                //当是2的N次幂时,i % radix 与i & mask是一样的效果
                buf[--charPos] = digits[i & mask];
                //无符号按位右移>>>,当左侧空出来的位,使用0填充,而不是使用符号位填充
                //这与按位右移不同>>,当左侧空出来的位,使用符号位填充
                i >>>= shift;
            } while (i != 0);
    
            return new String(buf, charPos, (32 - charPos));
        }

    七、highestOneBit(i) lowestOneBit(i)

    相关位操作,获取二进制中最高位1与最低位1表示的数字

        
        //来自于java.lang.Integer
        //获取二进制中最高位的1表示的数字
        public static int highestOneBit(int i) {
            // HD, Figure 3-1
            //最高位1的右边也成为了1
            i |= (i >>  1);
            //最高位1的右边1+2=3位以内都为1
            i |= (i >>  2); 
            //最高位1的右边1+2+4=7位以内都为1
            i |= (i >>  4); 
            //最高位1的右边1+2+4+8=15位以内都为1
            i |= (i >>  8); 
            //最高位1的右边1+2+4+8+16=31位以内都为1
            i |= (i >> 16);
            //最后将无符号右移相差就是最高位1表示的数字
            //或者i^(i>>>1)
            return i - (i >>> 1);
        }
    
        //同上
        //获取二进制中最低位1表示的数字
        public static int lowestOneBit(int i) {
            // HD, Section 2-1
            //如36,其二进制是00000000000000000000000000100100,则-i就是11111111111111111111111111011100,故最后结果为00000000000000000000000000000100,即是4.-i与i相比只有最末位的1是同处一个位置
            return i & -i;
        }

     备注:

    1、很多时候使用负数,很容易避免数据操作的溢出

    2、当数据在[-128,127]其是放在缓存中

    3、位操作在JDK源码中的运用还是挺多的,由于在某些情况下位操作比普通的加减乘除更加高效

    4、正数的原码、反码和补码是一样的,而负数的反码是其在原码的基础上除了符号位不变,其他位取反;且负数的补码是其在反码的基础上某位加1.

    5、Integer中的getInteger方法是获取系统属性对应的数值,decode将字符串解码为数值,接受十进制、八进制和十六进制。

    6、自动装箱和拆箱

    Integer a = 1;
    Integer b = 1;
    a == b:true
    先装箱Integer.valueOf(1),由于Integer有缓存-128~127
    int c = 1;
    c == b:true
    先装箱同上,之后拆箱Integer.intValue(),直接进行数值的比较
    
    a.equals(c):true
    先装箱Integer.valueOf(1),之后由于Integer.equals,是对Integer类型的比较,故同一中才能比较具体的数值大小,否则不能

    参考:

    http://www.hollischuang.com/archives/1058

    http://www.cnblogs.com/hanmou/p/3463984.html

    http://www.cnblogs.com/vinozly/p/5173477.html

    http://www.cnblogs.com/zhangziqiu/archive/2011/03/30/ComputerCode.html

  • 相关阅读:
    Ubuntu驱动程序开发2-Uboot命令使用
    Ubuntu驱动程序开发1-环境搭建
    STM32F4 串口IAP程序解析
    QT样式表(QSS)
    设备树常用OF函数
    UCOSIII在STM32f4上面的移植
    UCOS常用函数API
    MySQL学习——备份和还原
    JavaWeb学习——页面跳转方式
    Java问题记录——循环里的二次判断与状态更新
  • 原文地址:https://www.cnblogs.com/xiaoxian1369/p/5271315.html
Copyright © 2020-2023  润新知