Java基础(基本数据类型及自动装箱拆箱机制——源码剖析)

Java中的基本数据类型有8种,并且提供了相对应的引用类型:

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

自JDK1.5起,Java提供了自动装箱和拆箱机制,用于基本数据类型和引用类型之间的相互转化。
现以int与Integer为例,就二者之间的自动装箱与自动拆箱过程源码进行分析,并从源码角度对以下现象做出解释。

    System.out.println(Integer.valueOf(-1)==Integer.valueOf(-1));//结果为true
    System.out.println(Integer.valueOf(-1000)==Integer.valueOf(-1000));//结果为false

首先看一下Integer类的一个关键的构造方法:

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

接下来是int类型自动装箱方法的源代码:

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

该方法中有两个常量IntegerCache.low、IntegerCache.high和一个数组IntegerCache.cache[]。
代码显示当整型i ∈ [IntegerCache.low, IntegerCache.high]时,该方法返回的是IntegerCache.cache数组中下标为i + (-IntegerCache.low)的对象,否则会调用Integer的构造函数,创建一个value值为i的新Integer对象。

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

从代码中可以看出,该类是一个私有的静态类,并且构造方法是私有的。
在该类中,low是一个值固定为-128的int常量,而high是可配置的,默认为127,而cache数组中缓存的是[low, high]之间的Integer对象。因为Java支持数组的最大长度为Integer.MAX_VALUE,所以high的最大值不超过Integer.MAX_VALUE - (-low) -1。

在解释第一段代码的原因之前,首先需要明确的是,在Java中判断两个变量的值是否相等需要重写hashCode()方法和equals()方法,而==是判断两个变量引用的是否是同一个对象,即两个变量是否指向同一块内存地址。

根据上面的分析,调用两次Integer.valueOf(-1)返回的始终是存在于cache数组中的同一个Integer对象,故结果为true,而调用两次Integer.valueOf(-1000)返回的则是新创建的两个不同的Integer对象,故结果为false。

接下来介绍一下Integer的自动拆箱方法,方法很简单,就是调用返回该Integer对象的value属性:

    public int intValue() {
        return value;
    }

Java自动装箱和拆箱机制就介绍到这里,多看源码涨知识。

发布了2 篇原创文章 · 获赞 2 · 访问量 72

猜你喜欢

转载自blog.csdn.net/W_J_G_/article/details/104561351