Code前端首页关于Code前端联系我们

Java面试题:int和Integer有什么区别?

terry 2年前 (2023-09-25) 阅读数 50 #后端开发

问:int和Integer有什么区别?

答:Java几乎是一种纯粹的面向对象编程语言,只是为了方便编程而引入了基本数据类型。为了将这些基本数据类型作为对象进行管理,Java引入了相应的包装类(wrapper class),int的包装类就是Integer。从Java 5开始,引入了自动打包/解包机制,以便两者可以相互转换。
Java 为每种基本类型提供了包装类型:

  • 基本类型:Boolean、char、byte、short、int、long、float、double
  • 包装类型:Boolean、Character、Byte、Short、Integer、Long ,Float,Double
class AutoUnboxingTest {

    public static void main(String[] args) {
        Integer a = new Integer(3);
        Integer b = 3;                  // 将3自动装箱成Integer类型
        int c = 3;
        System.out.println(a == b);     // false 两个引用没有引用同一对象
        System.out.println(a == c);     // true a自动拆箱成int类型再和c比较
    }
}

java面试题:int和Integer有什么区别?

最近遇到一道面试题,也是和自动装箱拆箱有关。代码如下:

public class Test03 {

    public static void main(String[] args) {
        Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;

        System.out.println(f1 == f2);
        System.out.println(f3 == f4);
    }
}

java面试题:int和Integer有什么区别?

如果你不知道发生了什么,很容易认为两个输出都是 true 或者都是 false。首先要注意的是,四个变量f1、f2、f3、f4都是Integer对象的引用,所以下面的==操作不是比较值,而是引用。拳击的本质是什么?当我们给Integer对象赋值一个int值时,Integer类的静态valueOf方法将会被调用。如果你看看 valueOf 源代码,你就会知道发生了什么。

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

java面试题:int和Integer有什么区别?

IntegerCache 是 Integer 的内部类,其代码如下:

/**
     * 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 {@code -XX:AutoBoxCacheMax=<size>} 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) {
                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() {}
    }

java面试题:int和Integer有什么区别?

简单来说,如果一个整数字面量的值在 -128 到 127 之间,那么 new Integer 对象就不会 new 了,而是直接 new指的是常量组中的Integer对象,所以上面面试题中,结果f1==f2为真,结果f3==f4为假。

温馨提示:越是看似简单的面试问题,背后隐藏的秘密就越多,这对面试官的技巧要求很高。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门