一道面试题关于Integer的缓存范围(-128~127)所引起的一系列问题记录

某天无意中看见一道关于Integer的笔试题,问下面的输出结果是多少:

package test;

public class Test {

public static void main(String[] args) {  
    Integer i1 = 127;  
    Integer i2 = 127;  
    System.err.println(i1 == i2);  
      
    i1 = 128;  
    i2 = 128;  
    System.err.println(i1 == i2);  
}  

}
说实话,刚开始看到这题目自己并不确定答案,“==”对于引用类型比较的是对象地址是否相同,虽然java有自动拆箱和装箱,但这题一看就知道并不像自己想得那么简单,于是将代码粘贴到MyEclipse中运行,其输出结果:

看到这运行结果,自己怎么也想不通,为什么等于127的时候为true,128就变成false了呢?于是自己各种百度、谷歌,其中有一个解释是这样的:

JVM会自动维护八种基本类型的常量池,int常量池中初始化-128~127的范围,所以当为Integer i=127时,在自动装箱过程中是取自常量池中的数值,而当Integer i=128时,128不在常量池范围内,所以在自动装箱过程中需new 128,所以地址不一样。

于是自己就有了很多疑问:

1.如果是两个new 出来的Integer对象,但值在-128~127这个范围内并相等,再通过“==”去比较会怎么样呢?

测试代码如下:

package com.beauxie.javase;

public class Test2 {

public static void main(String[] args) {
    Integer i1 = 6;
    Integer i2 = 6;
    System.out.println((i1==i2));//true
    
    
    Integer i3 = new Integer(6);
    Integer i4 = new Integer(6);
    
    System.out.println((6==i3));
    System.out.println((128==i3));
    System.out.println((i4==128));
    
    System.out.println((i3==i4)+" "+i3.hashCode()+" "+i4.hashCode());
    
 }

}

}
在这里顺便打印出两个new出来的对象的hash值,运行结果:

以上结果说明:

a.当数值范围为-128~127时:如果两个new出来Integer对象,即使值相同,通过“”比较结果为false,但两个对象直接赋值,则通过“”比较结果为“true,这一点与String非常相似。

b.当数值不在-128~127时,无论通过哪种方式,即使两个对象的值相等,通过“==”比较,其结果为false;

c.当一个Integer对象直接与一个int基本数据类型通过“==”比较,其结果与第一点相同;

d.Integer对象的hash值为数值本身;

查看Integer源代码:
/**
* Returns a hash code for this {@code Integer}.
*
* @return a hash code value for this object, equal to the
* primitive {@code int} value represented by this
* {@code Integer} object.
*/
public int hashCode() {
return value;
}
Integer重写了hashCode方法,返回值是value,即Integer对象 的数值。

2.第二个问题,为什么Integer对象的范围是-128~127?

查看Integer类源码,发现里面有一个私有的静态内部类IntegerCache,而如果直接将一个基本数据类型的值赋给Integer对象,则会发生自动装箱,其原理就是通过调用Integer类的public static Integer valueOf(将int类型的值包装到一个对象中 ,其部分源码如下:

/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the -XX:AutoBoxCacheMax= option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/

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) {
            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);
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }

    private IntegerCache() {}
}



  /**
 * Returns an {@code Integer} instance representing the specified
 * {@code int} value.  If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 *
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 *
 * @param  i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since  1.5
 */
public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

查看API文档,对valueOf(int i)的方法描述如下:

我想通过以上的分析,应该知道原因了吧,简要的说就是在Integer类中有一个静态内部类IntegerCache,在IntegerCache类中有一个Integer数组,用以缓存当数值范围为-128~127时的Integer对象。

3.第三个问题是自己在百度有关该面试题相关知识时,无意中看见的一个问题,就是为何byte的范围是-128~127?

以下是网上搜来的答案:

一个字节占8bit,由于计算机只能识别二进制,即0和1。所以规定第一位是符号位,1表示负数,0表示正数,这里涉及到补码,如下图所示:

这也让我明白了为什么int的数值范围是 -231~231-1(int占4个字节,即32bit)。

一道小小的面试题居然花费了我这么多的时间、、、

原文:https://blog.csdn.net/BeauXie/article/details/53013946

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值