java基础类型包装类==判等

装箱:根据数据创建对应的包装对象。

Integer i = new Integer (5);
Integer j = 5;//jdk1.5 之后可以通过这种方式自动装箱

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

int  jValue = j.intValue();
int  iValue = i;//自动拆箱

Integer j = 5自动装箱时会调用方法:public static Integer valueOf(int i)

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

可以看到,当数值在IntegerCache.lowIntegerCache.high之间时,直接从缓存中取出,否则新建一个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() {}
}

可以发现通过数组cache[]保存数值在[-128,127]之间的Integer对象,所以对m、n自动装箱时,如果value在[-128,127]之间,每次自动装箱都会返回保存在缓存数组cache[]中的一个相同的Integer对象,即同一地址,用判等的话为true;如果value不在此区间,那每次自动装箱都会创建一个新的Integer对象,即不同的地址,用判等的话为false。

Integer m = value;
Integer n = value;
boolean isEqual1 = (m == n); //isEqual1 = ?
boolean isEqual2 = (m.equals(n));  //isEqual2 = true
posted @ 2021-09-05 22:10  codezhao  阅读(114)  评论(0)    收藏  举报