JDK源码阅读-Integer类

概要

Integer类包装一个对象中的原始类型int的值。此外,该类还提供了一些int和其他基本数据类型、String类型之间的互转,以及在处理int时有用的其他常量和方法。

类定义

public final class Integer extends Number implements Comparable<Integer>;
复制代码

从类定义中可看出:

  1. Integer是final类,不能被继承
  2. Integer实现了Comparable接口,因此存在compareTo(Integer i)方法
  3. Integer继承了Number类,因此需要实现不同基本数据类型之间的转换

构造方法

Integer有两个构造方法

public Integer(int value)

构造新分配的 Integer对象,该对象表示指定的int值。其实现简单的将入参赋给私有字段value

public Integer(int value){
    this.value = value;
}
复制代码

public Integer(String s) throws NumberFormatException

构造一个新分配Integer对象,表示字符串参数将转换为int值,正好与基数为parseInt方法一样。其调用了parseInt(java.lang.String, int)方法将入参字符串解析为int类型:

public Integer(String s) throws NumberFormatException {
    this.value = parseInt(s, 10);
}
复制代码

内部类IntegerCache

IntegerCache是Integer的一个内部类,主要包含了一个静态且final的cache数组,用来缓存部分经常用到的Integer对象,避免重复的实例化和回收。默认情况下,只缓存[-128,127]范围内的Integer对象。当新的一个Integer对象初始化时,如果其值再cache范围内则直接从缓存中获取对应的Integer对象,不必重新实例化。另外我们可以改变这些值缓存的范围,再启动JVM时通过-Djava.lang.Integer.IntegerCache.high=xxx就可以改变缓存值的最大值。

    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) {
                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() {}
    }

复制代码

字段

私有字段

value

Integer私有字段value真正保存其值的变量:private final int value;。value被定义成final类型,也就是说,一旦一个Integer对象使用第一种构造方法初始化后,value值就无法再改变了。初始化后如果尝试重新赋值,则会调用Integer.valueOf()来直接返回一个已有对象或新建一个对象,而不会改变原有的Integer对象。
如下代码:

public class IntegerTest{
    public static void main(String[] args){
        Integer i = new Integer(1);
        i = 2;
    }
}
复制代码

则编译之后的代码实际为:

public class IntegerTest{
    public Integer(){
    }
    
    public static void main(String[] args){
        Integer i = new Integer(1);
        i = Integer.valueOf(2);
    }
}
复制代码

default字段

digits

所有可以表示成一个数字的字符,支持2-36进制。

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'
    };
复制代码

DigitTens

个位上的数字数组

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',
        } ;
复制代码

DigitOnes

十位上的数字数组

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',
        } ;
复制代码

siteTable

配合stringSize()实现快速判断int变量的位数

final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
                                      99999999, 999999999, Integer.MAX_VALUE };
复制代码

公共字段

MIN_VALUE

静态常量。表示int的最小值,-231

@Native public static final int MIN_VALUE = 0x80000000;
复制代码

MAX_VALUE

静态常量。表示int的最大值,2^31-1

@Native public static final int MAX_VALUE = 0x7fffffff;
复制代码

TYPE

静态常量。基本数据类型的包装类中都有一个常量:TYPE,表示的是该包装类对应的基本数据类型的Class实例。因此存在Integer.TYPE==int.class;//trueInteger.TYPE==Integer.class

public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
复制代码

SIZE

静态常量。用来表示二进制补码形式的int值的比特数,值为32。

public static final int SIZE = 32;
复制代码

BYTES

静态常量。表示二进制补码形式的int值的字节数,值为4。

public static final int BYTES = SIZE / Byte.SIZE;
复制代码

方法

bitCount

类方法。用于统计二进制中"1"的个数

public static int bitCount(int i) {
        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;
    }
复制代码

详解参见:JDK源码阅读-Integer.bitCount()

xxxValue

实例方法。与其他数据类型间的类型转换,包括:

  • byteValue():转为byte型,需注意截断
public byte byteValue() {
        return (byte)value;
    }
复制代码
  • shortValue():转为short型,需注意截断
public short shortValue() {
        return (short)value;
    }
复制代码
  • intValue:获取其值
public int intValue(){
    return value;
}
复制代码
  • longValue(): 转为long型
public long longValue(){
    return (long) value;
}
复制代码
  • floatValue(): 转为float型
public float floatValue(){
    return (float) value;
}
复制代码
  • doubleValue(): 转为double型
public double longValue(){
    return (double) value;
}
复制代码

compare

类方法。比较两个int值的大小,0:相等;1:前者不小于后者; -1: 前者小于后者。

compare(int, int)

public static int compare(int x, int y){
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
复制代码

compare(Integer)

public static int compare(Integer antherInteger){
    return compare(this.value, anotherInteger.value);
}
复制代码

compareTo

实例方法。比较两个值的大小。

public int compareTo(Integer anotherInteger){
    return compare(this.value, anotherInteger.value);
}
复制代码

compareUnsigned

类方法。将两个参数看做无符号整数,比较大小。最大值是-1,因为在计算机中负数用补码存储,-1的补码为全1。方法实现中调用了compare(int, int),而compare比较的是有符号数。有符号数中,负数永远小于正数。这里将两个参数加上MIN_VALUE,即1000 0000 0000 0000 0000 0000 0000 0000,这样的话只改变数字的最高比特位(符号位),不影响后面的数值位。所以负数的最高位变成了0,正数的最高位变成了1,自然在compare函数里就分出大小来了。而非负数之间的比较并不受影响。since 1.8。

public static int compareUnsigned(int x, int y){
    return compare(x + MIN_VALUE, y + MIN_VALUE);
}
复制代码

parseInt

将整数字符串转成对应进制的int类型。与valueOf()相比,后者返回的是Integer类型。

parseInt(String s, int radix)

异常情况:

  1. 入参s为"null"或为空
  2. 入参radix超过Character中定义的进制许可范围: [2, 36]
  3. 入参s超过Integer范围
  4. 入参s存在不能由指定基数的数字表示的字符(除了减号)
public static int parseInt(String s, int radix) throws NumberFormatException{
    if (s == null){
        return new NumberFormatException("null");
    }
    
    if (radix < Character.MIN_RADIX) {
        return new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX");
    }
    
    if (radix > Character.MAX_RADIX) {
                return new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX");
    }
    
    int result = 0;
    boolean negative = false; //判断正负号的标记,先初始化为正数
    int i = 0, len = s.length();
    //初始化limit 为负,因为之后每次的result是相减的形式
    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; //上一次的结果乘以radix进制
            if (result < limit + digit) { // 处理溢出
                throw NumberFormatException.forInputString(s);
            }
            result -= digit;
        }
    } else {
        throw NumberFormatException.forInputString(s);
    }
    return negative ? result : -result;
}
复制代码

Q: 为啥要用减法来更新result,而不是直接用加法

parseInt(String)

直接调用parseInt(String, 10)方法。

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

valueOf

类方法。返回一个Integer对象,包含三种重载形式:

valueOf(int)

先尝试从缓存中获取已经实例化好的Integer对象,当获取失败后才会new一个新对象。因此希望将int变量装箱成Integer时,应使用valueOf()来代替构造函数。或直接使用Integer i = 100;,编译器会转成Integer i = Integer.valueOf(100)

public static Integer valueOf(int i){
    // 首先尝试从内部类IntegerCache的cache数组中获取
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    
    // cache不存在,则new一个新对象    
    return new Integer(i);
}
复制代码

valueOf(String)

所有能实现将String类型转成Integer(int)类型的方法,都是基于parseInt()方法实现的。

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}
复制代码

valueOf(String, int)

所有能实现将String类型转成Integer(int)类型的方法,都是基于parseInt()方法实现的。

public static Integer valueOf(String s, int radix) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, radix));
}
复制代码

decode(String)

将字符串解码为int,接受入参为以"0x"/"0X"/"#"打头的十六进制、以"0"打头的八进制,当然还有十进制的字符串。

    public static Integer decode(String nm) throws NumberFormatException {
        int radix = 10; // 默认十进制
        int index = 0;
        boolean negative = false;
        Integer result;

        if (nm.length() == 0)
            throw new NumberFormatException("Zero length string");
        char firstChar = nm.charAt(0);
        // Handle sign, if present
        if (firstChar == '-') {
            negative = true;
            index++;
        } else if (firstChar == '+')
            index++;

        // Handle radix specifier, if present
        if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { // 16进制
            index += 2;
            radix = 16;
        }
        else if (nm.startsWith("#", index)) { // 16进制
            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 = Integer.valueOf(nm.substring(index), radix);
            result = negative ? Integer.valueOf(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            // If number is Integer.MIN_VALUE, we'll end up here. The next line
            // handles this case, and causes any genuine format error to be
            // rethrown.
            String constant = negative ? ("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }
        return result;
    }
复制代码

调用demo:

Integer.decode("0Xffff"); // 输出65535
Integer.decode("0xffff"); // 输出65535
Integer.decode("#ffff"); // 输出65535
Integer.decode("077777777"); // 输出16777215
Integer.decode("-1234"); // 输出-1234
Integer.decode("+1234"); // 输出1234
Integer.decode("0888"); // 异常
Integer.decode(""); // 异常
Integer.decode("aa"); // 异常
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值