天天看点

深入理解java中的自动装箱与拆箱

、什么是装箱,什么是拆箱

装箱:把基本数据类型转换为包装类。

拆箱:把包装类转换为基本数据类型。

基本数据类型所对应的包装类:

int(几个字节4)- Integer

byte(1)- Byte

short(2)- Short

long(8)- Long

float(4)- Float

double(8)- Double

char(2)- Character

boolean(未定义)- Boolean

免费在线视频学习教程推荐:java视频教程

二、先来看看手动装箱和手动拆箱

例子:拿int和Integer举例

Integer i1=Integer.valueOf(3);

int i2=i1.intValue();

手动装箱是通过valueOf完成的,大家都知道 = 右边值赋给左边,3是一个int类型的,赋给左边就变成了Integer包装类。

手动拆箱是通过intValue()完成的,通过代码可以看到 i1 从Integer变成了int

三、手动看完了,来看自动的

为了减轻技术人员的工作,java从jdk1.5之后变为了自动装箱与拆箱,还拿上面那个举例:

手动:

Integer i1=Integer.valueOf(3);

int i2=i1.intValue();

自动

Integer i1=3;

int i2=i1;

这是已经默认自动装好和拆好了。

四、从几道题目中加深对自动装箱和拆箱的理解

(1)

Integer a = 100;

int b = 100;

System.out.println(a==b);结果为 true

原因:a 会自动拆箱和 b 进行比较,所以为 true

(2)

Integer a = 100;

Integer b = 100;

System.out.println(a==b);//结果为true

Integer a = 200;

Integer b = 200;

System.out.println(a==b);//结果为false

这就发生一个有意思的事了,为什么两个变量一样的,只有值不一样的一个是true,一个是false。

原因:这种情况就要说一下 == 这个比较符号了,== 比较的内存地址,也就是new 出来的对象的内存地址,看到这你们可能会问这好像没有new啊,但其实Integer a=200; 200前面是默认有 new Integer的,所用内存地址不一样 == 比较的就是 false了,但100为什么是true呢?这是因为 java中的常量池 我们可以点开 Integer的源码看看。

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;
}
           

在对 -128到127 之间的进行比较时,不会new 对象,而是直接到常量池中获取,所以100是true,200超过了这个范围然后进行了 new 的操作,所以内存地址是不同的。

(3)

Integer a = new Integer(100);

Integer b = 100;

System.out.println(a==b);

//结果为false

这跟上面那个100的差不多啊,从常量池中拿,为什么是false呢?