每日一道Java 基础面试题 — 自动装箱与拆箱

装箱就是自动将 基本数据类型 转换为 包装器类型(int–>Integer)

调用方法:Integer的valueOf(int) 方法

拆箱就是自动将 包装器类型 转换为 基本数据类型(Integer–>int)

调用方法:Integer的intValue方法

在Java SE5之前,如果要生成一个数值为10的Integer对象,必须这样进行:
Integer i = new Integer(10);
而在从Java SE5开始就提供了自动装箱的特性,如果要生成一个数值为10的Integer对象,只需要
这样就可以了:
Integer i = 10;

测试1: 以下代码会输出什么?

public class Test {
 public static void main(String[] args) {
 Integer i1 = 100;
 Integer i2 = 100;
 
 Integer i3 = 200;
 Integer i4 = 200;

 System.out.println(i1==i2);
 System.out.println(i3==i4);
 }
}

运行结果:

true
false

为什么会出现这样的结果?
输出结果表明 i1 和 i2 指向的是同一个对象,而i3和i4指向的是不同的对象。

让我们来一探究竟吧,下面这段代码是 Integer的valueOf方法的具体实现

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

IntegerCache类的实现

    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() {}
    }
在通过valueOf方法创建Integer对象的时候,如果数值在[-128,127]之间,便返回指向IntegerCache.cache中 已经存在的对象的引用;否则创建一个新的Integer对象。
上面的代码中 i1 和 i2 的数值为 100,因此会直接从 cache 中取已经存在的对象,所以i1和i2指向的是同一个对象,而i3和i4则是分别指向不同的对象。

测试2: 以下代码会输出什么?

public static void main(String[] args) {

 Double i1 = 100.0;
 Double i2 = 100.0;
 
 Double i3 = 200.0;
 Double i4 = 200.0;

 System.out.println(i1==i2);
 System.out.println(i3==i4);
 }

结果:

false
false

解释:在某个范围内整型数值的个数有限的,而浮点数却是无限的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值