码迷,mamicode.com
首页 > 编程语言 > 详细

Java中Long、Integer、Short、Byte的源码学习

时间:2016-03-13 11:20:15      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:

 

    
    //来自于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;
    }

 

    
    //来自于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‘,
    } ;

 

 

    
    //来自于java.lang.Integer
    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;
    }

 

 

    
    //来自于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

 

 

    
    //来自于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));
    }

 

参考:

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

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

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

Java中Long、Integer、Short、Byte的源码学习

标签:

原文地址:http://www.cnblogs.com/xiaoxian1369/p/5271315.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!