不是瞧不起各位,你可能没那么了解Integer

376 阅读5分钟

简介

Integer?

Integer 是数据类型之一 Integer 一个整型数据用来存储整数,整数包括正整数,负整数和零。

Integer与int的区别?

Integer:基础类型int的包装类,缺省值为null,必须实例化后才能使用 int: java基础类型,缺省值为0,可直接使用

类UML图

//类声明
public final class Integer extends Number implements Comparable<Integer> 

从代码实现和UML图分析

  1. 类由final标示,不可被其他类继承
  2. 继承 Number 抽象类用于实现 intValue...等基础类型转换方法
  3. Number抽象类 实现了 Serializable 接口,所以Integer可被序列化
  4. 实现 Comparable 接口实现 compareTo 方法实现数值比较

原创不易,燃烧秀发输出内容,如果有一丢丢收获,点个赞鼓励一下吧!还有个小惊喜,帮大家整理了一些技术电子书,关注《AIO生活》公众号回复“1024”即可获取~

解析

Integer类脑图

如图,在分析Integer类我把该类分成若干个部分

  1. 变量部分:按性质细分为静态变量成员变量
  2. 方法部分:按功能细分为构造方法,基础运算方法,位运算方法,类型转换方法,以及其他未归类的普通方法.
  3. 内部类部分:integerCache缓存类

静态变量以及成员变量

    //成员变量(基本类型int的值)
    private final int value;
    //min_value ->-2147483647 -2的31次方
    @Native public static final int   MIN_VALUE = 0x80000000;
    //max_value ->2147483647 2的31次方
    @Native public static final int   MAX_VALUE = 0x7fffffff;
    //声明Integer类的原始类型为int
    public static final Class<Integer>  TYPE = (Class<Integer>)     Class.getPrimitiveClass("int");
    //用来表示二进制补码形式的int值的字节数,值为SIZE除于Byte.SIZE,结果为4
    public static final int BYTES = SIZE / Byte.SIZE;
    //方便取出int型数字对应字符串的长度
    final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
                                      99999999, 999999999, Integer.MAX_VALUE };
    //数字字母表,表示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'
    };
    //方便取出0-99的数个位和十位的值,如39 DigitTens[39]=3,DigitOnes[39]=9
    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',
        } ;
    //序列化序号
    @Native private static final long serialVersionUID = 1360826667806852920L;

方法

构造方法

定义:传入基本类型intString构造Integer对象

    //构造方法,初始化value为传入的值
    public Integer(int value) {
        this.value = value;
    }
    //构造方法,传入一个字符串类型的值,失败会抛出数值转换异常
    public Integer(String s) throws NumberFormatException {
        //值先转成int
        this.value = parseInt(s, 10);
    }

valueOf

定义:类型转换为Integer包装类

    //当取值为-127->128时,会取缓存里的数据
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    //传入String类型数值返回Integer的包装对象,失败返回数值转换异常
    public static Integer valueOf(String s) throws NumberFormatException {
        //转化为十进制的int值后传入valueOf(int i)
        return Integer.valueOf(parseInt(s, 10));
    }
    //传入String类型数值返回Integer的包装对象,radix值定义转换的Integer的进制数字,失败返回数值转换异常
    public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return Integer.valueOf(parseInt(s,radix));
    }

toString系列

定义:转换成对应格式的String类型返回

    //返回String类型,非静态方法.内部直接调用toString(int i),i为成员变量value,返回String字符串
    public String toString() {
        return toString(value);
    }

    //如果是int的最小值,直接返回,防止在getChars方法中溢出.其他int值,计算出数字位数,调用getChars方法得到char[],最后通过String的构造方法返回String类型对象.
    public static String toString(int i) {
        //特殊处理,因为int的最小值会溢出
        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);
    }

    //转换为radix进制的字符串
    public static String toString(int i, int radix) {
        //如果输入的radix进制不是有效进制,默认十进制
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        /* Use the faster version */
        //如果是十进制,直接调用一个参数的toString
        if (radix == 10) {
            return toString(i);
        }

        //int型为32位,加上符号位,最长可以为33位,故先创建一个33位的char数组
        char buf[] = new char[33];
        boolean negative = (i < 0);
        int charPos = 32;

        //判断是否是负数,如果不是则转为负数
        if (!negative) {
            i = -i;
        }

        //int型的最大值为2147483647,最小值为 -2147483648;
        //如果将负数转为正数,最小值在转时会溢出,故使用负数来进行运行
        while (i <= -radix) {
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        buf[charPos] = digits[-i];

        if (negative) {
            buf[--charPos] = '-';
        }

        //根据buf数组、数组有效值位置charPos以及有效长度33-charPos创建一个string对象
        return new String(buf, charPos, (33 - charPos));
    }

    //转为对应的进制字符串,内部调用toUnsignedString0方法
    //转为二进制字符串
    public static String toBinaryString(int i) {
        return toUnsignedString0(i, 1);
    }
    //转为八进制字符串
    public static String toOctalString(int i) {
        return toUnsignedString0(i, 3);
    }
    //转为十六进制字符串
    public static String toHexString(int i) {
        return toUnsignedString0(i, 4);
    }
    private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        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);
    }

getInteger

定义:经常会被错误用做是获取Integer对象值.他的正确用法是获取系统变量转换为Integer.

    //获取变量名为nm的系统变量,值转为Integer
    public static Integer getInteger(String nm) {
        return getInteger(nm, null);
    }
    //获取变量名为nm的系统变量,值转为Integer,val为默认值
    public static Integer getInteger(String nm, int val) {
        Integer result = getInteger(nm, null);
        return (result == null) ? Integer.valueOf(val) : result;
    }
    //获取变量名为nm的系统变量,值转为Integer,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;
    }

parseInt

定义:将字符串参数解析为有符号的基本类型int

    //默认转换为int类型,转换基数为10(进制)
    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

    //转换为int的构造方法,radix表示基数
    public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        //为空直接抛出数值转换异常
        if (s == null) {
            throw new NumberFormatException("null");
        }
        //判断进制在2-36之间,保证是合理的进制值
        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++;
            }
            //limit负数为int最小值,正数为-int最大值,与进制基数相除计算临界值
            multmin = limit / radix;
            while (i < len) {
                // 通过char类型对应的ASCII码以及进制找到对应的进制int值
                /// https://tool.ip138.com/ascii_code/ ASCII对照表
                digit = Character.digit(s.charAt(i++),radix);
                //如果没有匹配到抛出异常
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                //如果追加超过了溢出阈值抛出异常
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                //第一次循环,result为0,这里计算还是为0
                //第二次循环,result赋值为字符串的第 i 位与进制基数相乘
                //.........
                result *= radix;
                //result小于溢出阈值与追加值的和抛出转换异常
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                //result等于result减去追加值
                result -= digit;
            }
        } else {
            //空字符返回类型转换异常
            throw NumberFormatException.forInputString(s);
        }
        //符号为正负.result添加对应符号
        return negative ? result : -result;
    }

parseUnsignedInt

定义:将字符串参数解析为无符号的整数

    //转换为无符号int值,默认基数10
        public static int parseUnsignedInt(String s) throws NumberFormatException {
            return parseUnsignedInt(s, 10);
    }

    //String转换为无符号int值
    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 {
                //如果没有超过int最大值,就直接调用parseInt直接转换成int值
                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 {
                    //如果超过int最大值,需要进行无符号转换,
                    //因为超过了int的最大值,需要升级为long类型.
                    long ell = Long.parseLong(s, radix);
                    //与运算是当前位同1为1.没有超过0xffffffff00000000的部分都为0.直接进行int强制转换
                    if ((ell & 0xffff_ffff_0000_0000L) == 0) {
                        return (int) ell;
                    } else {
                        //界限为0xffffffff00000000:int最大值+int最小值的绝对值,超出表示不可以被转换
                        throw new
                            NumberFormatException(String.format("String value %s exceeds " +
                                                                "range of unsigned int.", s));
                    }
                }
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
    }

基础类型转换方法

    //实现抽象Number类的基础转换方法
    //返回基本类型int
    public int intValue() {
        return value;
    }
    //返回基本类型long
    public long longValue() {
        return (long)value;
    }
    //返回基本类型float
    public float floatValue() {
        return (float)value;
    }
    //返回基本类型double
    public double doubleValue() {
        return (double)value;
    }
    //返回基本类型short
    public short shortValue() {
        return (short)value;
    }
    //返回基本类型byte
    public byte byteValue() {
        return (byte)value;
    }

内部类 IntegerCache

    //integer的缓存类,缓存-128->127的数据,猜测场景订单的交易数量,大多数都是100以内的价格,
    // 用了IntegerCache,就减少了new的时间也就提升了效率。同时JDK还提供cache中high值得可配置,方便对JVM进行优化
    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
            //初始化缓存的最高值 -218 +127
            int h = 127;
            //缓存的最高值可以通过配置灵活变动
            //-Djava.lang.Integer.IntegerCache.high=xxx
            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的长度为最大的high-low+1的值,默认为256
            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使内部类无法实例化
        private IntegerCache() {}
    }

缓存内部类经典面试题.

    //引出经典面试题,所以integer比较时用equals比较
    Integer a = 127, b = 127, c = 129, d = 129;
    log.info("use integer cache ->{}", a == b);
    log.info("not use integer cache ->{}", c == d);

    //输出
    [main] INFO lang.TestInteger - use integer cache ->true
    [main] INFO lang.TestInteger - not use integer cache ->false

    //因为直接赋值Integer对象会调用valueOf(int i)方法,上面有介绍,这个方法在-127~128(默认)的情况下会直接取缓存.所以他们的值引用是相等的.
      但是当超过了`最大缓存值`,会调用构造方法new一个对象.导致他们的引用地址不相等.

最后

原创不易,燃烧秀发输出内容,如果有一丢丢收获,点个赞鼓励一下吧!还有个小惊喜,帮大家整理了一些技术电子书,关注公众号回复“1024”即可获取~