学习笔记之自动装箱与拆箱

自动拆箱与装箱

什么是拆箱与装箱?

拆箱:将基本类型用他们对应的引用类型包装起来。
装箱:将包装类型转换成基本数据类型。

基本类型与引用类型

基本类型引用类型
byteByte
shortShort
intInteger
longLong
doubleDouble
floatFloat
charCharacter
booleanBoolean

在Java1.5之前,没有提供自动装箱时,要生成一个数值为1的Integer对象时,需要这样做:

Integer i=new Integer(1);

在Java5之后,仅需要这要做就行了:

Integer i=1

省略的这个过程就是根据数值创建对应的 Integer对象,这就是装箱

同样的,拆箱与之对立,就是将包装类型拆成基本类型:

Integer i = 1;  //装箱
int n = i;   //拆箱

拆装箱如何实现的?

public class Main {
    public static void main(String[] args) {
         
        Integer i = 1;
        int n = i;
    }
}

在Java5之前我们做int基本数据类型和Integer引用类型相互转换需要这样:

public class MyDemo {
    private static int i=1;

    public static void zxcx() {
        Integer n = Integer.valueOf(i);//调用静态方法valueOf,将int转为Integer
        int x = n.intValue();//调用Integer.intValue()方法转为int类型
    }
}

其实我们可以看一下Integer的部分源码就不难发现自动装/拆箱帮我们做了什么:

public final class Integer extends Number implements Comparable<Integer> {

	private final int value;
	
	//构造器
	public Integer(int value) {
        this.value = value;
    }

	//Integer类型对象调用该方法,返回int类型
	public int intValue() {
        return value;
    }
	
	//该静态方法可以将int类型转换为Integer对象类型
	public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)//注意这里有一个if判断,这里多了一个IntegerCache类
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
}

以Integer为例,举一个与面试相关的题目

如果这行这段代码会得到什么结果?

public class Main {
    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);
    }
}

在不了解Integer缓存的情况下,我们觉得可能会都输出true,或者都输出flase;
但是结果:

true
false

那为什么两个值都为100的Integer对象是同一个对象,值为200的两个Integer对象不是同一个对象呢?
我们来看一下IntegerCache的源码:

//这是Integer类的内部类,而且被static修饰,也就是说,在虚拟机启动的时候,该类已经被加载到内存中
    private static class IntegerCache {
        static final int low = -128;//这里是定义的静态的final的low,为-128
        static final int high;
        static final Integer cache[];//一个静态的Integer类型的数组

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

其中,我们不难看出这个缓存就是为Integer做了一个-128—127这样的一个数组缓存;当我们要进行装箱时,调用的 valueOf(int i)的方法中 i 的数值在-128—127之间,就会从IntegerCache中读取已经创建的对象;不需要再创建一个新的对象;显然100在范围内,200已经超出这个范围;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值