java源码阅读-Integer类

public final class Integer extends Number implements Comparable

从类定义可以看出Integer不可以被继承,继承了Number类,实现了Comparable

    @SuppressWarnings("unchecked")
    public static final Class  TYPE = (Class) Class.getPrimitiveClass("int");

Integer.TYPE取得是基本数据类型int的class

 public static String toString(int i, int radix)

这个方法是返回对应进制的转为string的数

    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 int numberOfLeadingZeros(long i) 

获取数字中有多少个0

    /**
     * 将integer转换为无符号数字 shift 二进制1 八进制3 十六进制4
     */
    private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        //32减去val中为0的部分的长度
        int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
        //如果是二进制的话 那就是mag
        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;
        //进制-1 二进制1 八进制111 十六进制1111
        int mask = radix - 1;
        //将数字转化为对应的进制
        do {
            buf[offset + --charPos] = Integer.digits[val & mask];
            val >>>= shift;
        } while (val != 0 && charPos > 0);

        return charPos;
    }

将string类型转为int

 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大于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();
        //MAX_VALUE = 0x7fffffff;
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // 有可能以+或者-开头
                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;//猜测multmin是数字的长度
            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;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }

Integer类中的缓存
表示缓存从-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;
            //获取系统配置文件中的high配置
            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() {}
    }

自动拆装箱用的就是valueOf()
如果在缓存命中范围内 那么就用缓存的,不然new一个

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

hashcode返回本身

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

equals方法

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

你可能感兴趣的:(java源码阅读-Integer类)