Java后台开发面试

来源:互联网 发布:头脑风暴软件 编辑:程序博客网 时间:2024/05/16 08:36

面试题:int和Integer的区别?什么时候用int,什么时候用Integer?

  • 解析
    Java提供了两种不同的类型:引用类型和基本类型。为实现基本数据类型到面向对象的转化,Java为每个基本数据类型提供了对应的包装类(或者叫作封装类),如下表所示:

    表-基本数据类型对应的包装类 

基本数据类型 包装类 基本数据类型 包装类 boolean Boolean float Float byte Byte int Integer char Character long Long double Double short Short

引用类型和基本类型的行为完全不同,并且它们具有不同的语义、特征和用法。另外,对象引用实例变量的默认值为null,而基本类型实例变量的默认值与它们的类型有关。

int和Integer的区别:

  int是java的基本数据类型,Integer是Java为int提供的封装类。

int是基本数据类型,Integer是引用类型。当要装入ArrayList、HashMap等容器时,需要作为对象来装入,此时选择Integer。因为容器都是装object的。

int 初始化
int i =1;
int默认值是0

Integer 初始化
Integer i= new Integer(1);
Integer 默认值是null

根据int和Integer默认值不同,确定不同的使用场景。比如,可以用Integer来表示没有参加考试,用int表示考试成绩为0。

下面还想强调一点:

Integer ina = 2;Integer inb = 2;System.out.println("两个2自动装箱后是否相等:" + (ina == inb));  //  输出trueInteger biga = 128;Integer bigb = 128;System.out.println("两个128自动装箱后是否相等:" + (biga == bigb));//  输出false

同样是两个int类型的数值自动装箱成Integer实例后,如果是两个2自动装箱后就相等;但如果是两个128自动装箱后就不相同,为什么呢?从源码中找答案。

查看 Java系统中java.lang.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 -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) {                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() {}    }

IntegerCache类Integer类中一个私有的静态类。IntegerCache类是用来实现缓存支持的,并支持-128127之间的自动装箱过程。这个缓存会在Integer类第一次被使用时被初始化。以后,在创建新的Integer对象之前,会先在IntegerCache.cache中查找。

因此,-128到127之间的同一个整数自动装箱成Integer实例时,永远都是引用cache数组的同一个数组元素,所以它们全部相等;但每次把一个不在-128到127范围内的整数自动装箱成Integer实例时,系统总是会重新创建一个Integer实例,所以两个128自动装箱成Integer实例后就不相等。

原创粉丝点击