java 自动装箱、拆箱

# java 自动装箱、拆箱

jdk 1.5 版本开始, 引入该功能。

一、自动装箱

基本数据类型自动封装为对应封装类。

代码示例,

Integer i = 100;

100属于基本类型int,会自动装箱,如下:

Integer i = Integer.valueOf(100);

相当于,

Integer i = new Integer(100);

二、自动拆箱

将封装类自动转换为对应的基本数据类型

代码示例,

Integer i = new Integer(100);
int j = i;

i属于封装类Integer,会自动拆箱,如下:

Integer i = new Integer(100);
int j = i.intValue();

三、问题

  • 三目运算符

问题代码(会引起NPE问题),

Map<String, Boolean> map = new HashMap<String, Boolean>();
Boolean b = (map != null ? map.get("test") : false);

问题原因:三目运算符第二、三操作数类型不同(一个为对象,一个为基本数据类型),会将对象自动拆箱为基本数据类型。

拆箱过程,

Map<String, Boolean> map = new HashMap<String, Boolean>();
Boolean b = Boolean.valueOf(map != null ? map.get("test").booleanValue() : false);

问题解决,

Map<String, Boolean> map = new HashMap<String, Boolean>();
Boolean b = (map != null ? map.get("test") : Boolean.FALSE);
  • Integer

相关代码,

Integer int1 = 100;
Integer int2 = 100;
Integer int3 = 300;
Integer int4 = 300;
    
// true
System.out.println(int1 == int2);
// false
System.out.println(int3 == int4);

引起问题原因:装箱调用了Integer.valueOf()。源码如下,

public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    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) {
            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.high取值为127。因此,通过Integer.valueOf()方法创建Integer对象的时候,如果数值在[-128,127]之间,返回IntegerCache.cache中对象的引用,否则创建一个新的Integer对象。

猜你喜欢

转载自www.cnblogs.com/wscy/p/9176850.html