Integer-源码

Integer 是java5 引进的新特性

先上一个小实验:

 public static void main(String[] args) {
        Integer a1 = 100;
        Integer a2 = 100;
        System.out.println(a1 == a2);
        Integer b1 = 1000;
        Integer b2 = 1000;
        System.out.println(b1 == b2);
    }


结果:
    
true
false

Process finished with exit code 0

先说结论,[-128,127] 这个区间 true ,其他的范围为 new 一个新的对象。

分析:

查看字节码

public static main([Ljava/lang/String;)V
   L0
    LINENUMBER 7 L0
    BIPUSH 100
    INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;
    ASTORE 1
   L1
    LINENUMBER 8 L1
    BIPUSH 100
    INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;
    ASTORE 2
                    
…………

代码实际上是Integer.valueOf

    public static Integer valueOf(int i) {
        //缓存在数组,相应对象直接返回
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        //不在缓存,则会new一个
        return new Integer(i);
    }

IntegerCache 是 Integer 的一个匿名内部类

这也是自动装箱的代码实现。

JAVA将基本类型自动转换为包装类的过程称为自动装箱(autoboxing)。

实际上在 Java 5 中引入这个特性的时候,范围是固定的 -128 至 +127。

后来在Java 6 后,最大值映射到 java.lang.Integer.IntegerCache.high,可以使用 JVM 的启动参数设置最大值。(通过 JVM 的启动参数 -XX:AutoBoxCacheMax=size 修改)

缓存通过一个 for 循环实现。从小到大的创建尽可能多的整数并存储在一个名为 cache 的整数数组中。

这个缓存会在 Integer 类第一次被使用的时候被初始化出来。以后,就可以使用缓存中包含的实例对象,而不是创建一个新的实例(在自动装箱的情况下)。

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

所有整数类型的类都有类似的缓存机制:

有 ByteCache 用于缓存 Byte 对象

有 ShortCache 用于缓存 Short 对象

有 LongCache 用于缓存 Long 对象

Byte,Short,Long 的缓存池范围默认都是: -128 到 127。可以看出,Byte的所有值都在缓存区中,用它生成的相同值对象都是相等的。

所有整型(Byte,Short,Long)的比较规律与Integer是一样的。

同时Character 对象也有CharacterCache 缓存 池,范围是 0 到 127。

除了 Integer 可以通过参数改变范围外,其它的都不行。

参考链接:

https://zhuanlan.zhihu.com/p/27562748
https://blog.csdn.net/maihilton/article/details/80101497?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control

`Integer.parseInt()` 函数的具体实现如下: ```java public static int parseInt(String s) throws NumberFormatException { return parseInt(s,10); } public static int parseInt(String s, int radix) throws NumberFormatException { 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') { //处理负数 if (firstChar == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (firstChar != '+') throw NumberFormatException.forInputString(s); if (len == 1) // 如果只有一个符号,则抛出异常 throw NumberFormatException.forInputString(s); i++; } multmin = limit / radix; while (i < len) { 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; } ``` 在实现中,`parseInt()` 函数会先将传入的字符串转换为整数,如果转换失败则会抛出 `NumberFormatException` 异常。它的具体实现过程如下: 1. 首先判断传入的参数是否为 `null`,如果是则抛出异常; 2. 然后判断传入的进制数是否合法,如果不在 `2` 到 `36` 的范围内则抛出异常; 3. 接着判断字符串的第一个字符,如果是 `-` 则表示是负数,否则如果是 `+` 则忽略; 4. 如果字符串只有一个符号则抛出异常; 5. 从字符串的第一个有效数字开始,按照进制数将每个字符转换为数字,然后计算出整数; 6. 如果字符串中包含非数字字符,则抛出异常; 7. 如果整数超出了 `int` 类型的范围,则抛出异常; 8. 如果字符串的长度为 `0`,则抛出异常; 9. 最后将整数返回。 需要注意的是,在实现中,`parseInt()` 函数会使用 `Character.digit()` 函数将字符转换为数字。如果字符不是数字,则返回 `-1`。如果传入的字符串包含非数字字符,则会在第一次调用 `digit()` 函数时抛出异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值