java源码-Integer原码分析

186 阅读4分钟
/*建议复制在IDEA等编辑器中打开,方便查看代码调用*/

import java.lang.annotation.Native;
public final class Integer extends Number implements Comparable<java.lang.Integer> {

    @Native
    public static final int MIN_VALUE = 0x80000000;

    @Native
    public static final int MAX_VALUE = 0x7fffffff;

    @SuppressWarnings("unchecked")
    public static final Class<java.lang.Integer> TYPE = (Class<java.lang.Integer>) Class.getPrimitiveClass("int");

    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'
    };

    /**
     * 将10进制数转成radix进制的字符串
     */
    public static String toString(int i, int radix) {
        //超过进制上下限则取值为10进制
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        //若是10进制
        if (radix == 10) {
            return toString(i);
        }
        //定义字符数组为33,32位加上符号位
        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));
    }

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

    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);
    }

    private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        int mag = java.lang.Integer.SIZE - java.lang.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);
    }

    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 {
            buf[offset + --charPos] = java.lang.Integer.digits[val & mask];
            val >>>= shift;
        } while (val != 0 && charPos > 0);

        return charPos;
    }

    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',
    };

    /**
     * 将value转成十进制字符串
     */
    public static String toString(int i) {
        //若是最小值直接返回
        if (i == java.lang.Integer.MIN_VALUE)
            return "-2147483648";
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        //计算i的十进制数每位上面的数字并放入buf中
        getChars(i, size, buf);
        //返回String
        return new String(buf, true);
    }

    /**
     * 计算传入值i的十进制每位上面的数字并放入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;
            // 相当于 r = i - (q * 100); 即取出个位和十位
            r = i - ((q << 6) + (q << 5) + (q << 2));
            //给你i重新赋值,满足条件则继续循环
            i = q;
            //取出个位,放在数组中
            buf[--charPos] = DigitOnes[r];
            //取出十位,放在数组中
            buf[--charPos] = DigitTens[r];
        }

        //当i<65536时
        for (; ; ) {
            //取出十位及以上数字
            q = (i * 52429) >>> (16 + 3);
            // 相当于 r = i-(q*10); 即取出个位
            r = i - ((q << 3) + (q << 1));
            buf[--charPos] = digits[r];
            i = q;
            if (i == 0) break;
        }
        //若符号存在,数组中放入符号位
        if (sign != 0) {
            buf[--charPos] = sign;
        }
    }

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

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

    // x是正整数
    //计算int的位数并加1
    static int stringSize(int x) {
        for (int i = 0; ; i++)
            if (x <= sizeTable[i])
                return i + 1;
    }

    /**
     * 将字符串转换成int
     *
     * @param s     数字字符串
     * @param radix 进制
     */
    public static int parseInt(String s, int radix)
            throws NumberFormatException {
        /*
         * 警告:此方法可能在VM初始化期间*初始化IntegerCache之前提早调用。
         * 必须注意不要使用valueOf方法。
         */
        if (s == null) {
            throw new NumberFormatException("null");
        }
        //检查传入的进制数是否小于2
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                    " less than Character.MIN_RADIX");
        }
        //检查传入的进制数是否大于36
        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 = -java.lang.Integer.MAX_VALUE;
        int multmin;
        int digit;
        //字符串长度>0
        if (len > 0) {
            //取出首字符
            char firstChar = s.charAt(0);
            //若首字符的ASCII码小于'0'的ASCII码,则字符有可能是+或者-
            if (firstChar < '0') {
                if (firstChar == '-') {
                    //负数符号标识设置为true
                    negative = true;
                    //上限设为java.lang.Integer.MIN_VALUE
                    limit = java.lang.Integer.MIN_VALUE;
                    //若是符号不是-也不是+,则抛出 NumberFormatException
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);
                //若数字字符串仅有"+" 或者 "-"一个字符
                if (len == 1)
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            //得到进制的倍数,若是正数则该值为负,负数该值为正
            multmin = limit / radix;
            while (i < len) {
                //获取字符在radix进制中的数值
                digit = Character.digit(s.charAt(i++), radix);
                //该值不可能<0
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                //判断是否可以追加计算下一个数字,
                // result若是<multmin,则继续追加下一个数字会逸出上下限
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                //结果乘上进制
                result *= radix;
                //若是result < limit + digit为true,说明大于上下限
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                //累计结果,结果是负的
                result -= digit;
            }
        } else {
            //字符串长度<0抛出异常
            throw NumberFormatException.forInputString(s);
        }
        //因为result是负的所以若是负数直接返回,正数则取反
        return negative ? result : -result;
    }

    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s, 10);
    }

    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);
        }
    }

    public static int parseUnsignedInt(String s) throws NumberFormatException {
        return parseUnsignedInt(s, 10);
    }

    public static java.lang.Integer valueOf(String s, int radix) throws NumberFormatException {
        return java.lang.Integer.valueOf(parseInt(s, radix));
    }

    public static java.lang.Integer valueOf(String s) throws NumberFormatException {
        return java.lang.Integer.valueOf(parseInt(s, 10));
    }

    /**
     * 缓存类 缓存的最小值为-128 最大值默认为 127,可通过vm参数 java.lang.Integer.IntegerCache.high 调整
     */
    private static class IntegerCache {
        //在low和high之间的值都会先初始化到缓存,之后直接使用缓存中的值,不需要重新创建对象
        static final int low = -128;
        static final int high;
        static final java.lang.Integer cache[];

        static {
            // 设置缓存最大值的默认值
            int h = 127;
            String integerCacheHighPropValue =
                    sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            //vm参数有设置
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    //设置vm参数和127中较大的值
                    i = Math.max(i, 127);
                    //java.lang.Integer.MAX_VALUE - (-low) - 1 表示high的最大允许值
                    //确保high不超过最大值
                    h = Math.min(i, java.lang.Integer.MAX_VALUE - (-low) - 1);
                } catch (NumberFormatException nfe) {
                    // 如果无法将属性解析为int,则忽略
                }
            }
            high = h;
            //创建缓存数组
            cache = new java.lang.Integer[(high - low) + 1];
            int j = low;
            //初始化缓存值
            for (int k = 0; k < cache.length; k++)
                cache[k] = new java.lang.Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert java.lang.Integer.IntegerCache.high >= 127;
        }

        private IntegerCache() {
        }
    }

    /**
     * 此方法在自动装箱的时候会调用
     */
    public static java.lang.Integer valueOf(int i) {
        //int参数是否在缓存范围内
        if (i >= java.lang.Integer.IntegerCache.low && i <= java.lang.Integer.IntegerCache.high)
            // 是,则取缓存的对象返回
            return java.lang.Integer.IntegerCache.cache[i + (-java.lang.Integer.IntegerCache.low)];
        //否,则直接创建新对像
        return new java.lang.Integer(i);
    }

    /**
     * 存包装类值的成员变量
     */
    private final int value;

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

    /**
     * 传入String参数的构造方法
     *
     * @param s 传入的字符串类型的数字
     * @throws NumberFormatException
     */
    public Integer(String s) throws NumberFormatException {
        //调用parseInt方法,默认使用10进制
        this.value = parseInt(s, 10);
    }

    //以下几个基础类型+Value开头的方法均是Number接口的实现,用于类型转换,除了int外都是强转
    public byte byteValue() {
        return (byte) value;
    }

    public short shortValue() {
        return (short) value;
    }

    public int intValue() {
        return value;
    }

    public long longValue() {
        return (long) value;
    }

    public float floatValue() {
        return (float) value;
    }

    public double doubleValue() {
        return (double) value;
    }

    /**
     * 重写Object对象的toString方法
     *
     * @return
     */
    public String toString() {
        //调用本类中的toString(int)方法
        return toString(value);
    }

    @Override
    public int hashCode() {
        return java.lang.Integer.hashCode(value);
    }

    public static int hashCode(int value) {
        return value;
    }

    public boolean equals(Object obj) {
        if (obj instanceof java.lang.Integer) {
            return value == ((java.lang.Integer) obj).intValue();
        }
        return false;
    }

    public static java.lang.Integer getInteger(String nm) {
        return getInteger(nm, null);
    }

    /**
     * 获取属性名为nm的系统参数,没有值则为val
     */
    public static java.lang.Integer getInteger(String nm, int val) {
        java.lang.Integer result = getInteger(nm, null);
        return (result == null) ? java.lang.Integer.valueOf(val) : result;
    }

    /**
     *
     * 获取属性名为nm的系统参数,没有值则为val
     */
    public static java.lang.Integer getInteger(String nm, java.lang.Integer val) {
        String v = null;
        try {
            v = System.getProperty(nm);
        } catch (IllegalArgumentException | NullPointerException e) {
        }
        if (v != null) {
            try {
                return java.lang.Integer.decode(v);
            } catch (NumberFormatException e) {
            }
        }
        return val;
    }

    /**
     * 将系统属性设置的字符串转为Integer对象
     */
    public static java.lang.Integer decode(String nm) throws NumberFormatException {
        int radix = 10;
        int index = 0;
        boolean negative = false;
        java.lang.Integer result;

        if (nm.length() == 0)
            throw new NumberFormatException("Zero length string");
        //取首字符
        char firstChar = nm.charAt(0);
        //判断 + - 号
        if (firstChar == '-') {
            negative = true;
            index++;
        } else if (firstChar == '+')
            index++;

        //处理进制符号
        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 = java.lang.Integer.valueOf(nm.substring(index), radix);
            result = negative ? java.lang.Integer.valueOf(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            //截取掉超过最大值部分字符
            String constant = negative ? ("-" + nm.substring(index))
                    : nm.substring(index);
            result = java.lang.Integer.valueOf(constant, radix);
        }
        return result;
    }

    public int compareTo(java.lang.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 static int compareUnsigned(int x, int y) {
        return compare(x + MIN_VALUE, y + MIN_VALUE);
    }

    public static long toUnsignedLong(int x) {
        return ((long) x) & 0xffffffffL;
    }

    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));
    }

    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));
    }

    @Native
    public static final int SIZE = 32;

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

    /**
     * 取最高位的二进制数值
     */
    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);
    }
    /**
     * 取最高低的二进制数值
     */
    public static int lowestOneBit(int i) {
        // HD, Section 2-1
        return i & -i;
    }

    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;
    }

    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的个数
     */
    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;
    }

    public static int rotateLeft(int i, int distance) {
        return (i << distance) | (i >>> -distance);
    }

    public static int rotateRight(int i, int distance) {
        return (i >>> distance) | (i << -distance);
    }

    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;
    }

    public static int signum(int i) {
        // HD, Section 2-7
        return (i >> 31) | (-i >>> 31);
    }

    public static int reverseBytes(int i) {
        return ((i >>> 24)) |
                ((i >> 8) & 0xFF00) |
                ((i << 8) & 0xFF0000) |
                ((i << 24));
    }

    public static int sum(int a, int b) {
        return a + b;
    }

    public static int max(int a, int b) {
        return Math.max(a, b);
    }

    public static int min(int a, int b) {
        return Math.min(a, b);
    }

    @Native
    private static final long serialVersionUID = 1360826667806852920L;
}