包装类

结论先行:包装类对象之前进行比较是否相等时,使用equals(),或使用的对应的拆箱进行比较

1、自动装箱
基本类型就自动地封装到与它相同类型的包装中,如:
Integer i = 100;
本质上,编译器编译时添加了:
Integer i = Integer.valueOf(100);


2、自动拆箱
包装类对象自动转换成基本类型数据。如:
int a = new Integer(100);
本质上,编译器在编译时添加了:
int a = new Integer(100).intValue();

public class BoxingDemo {//装箱和拆箱
    public static void main(String[] args) {

        Integer ii = 1000;
        int ii1 = ii;
        System.out.println(ii == ii1);//true
        Integer i = 1000;
        int i1 = 1000;
        System.out.println(i == i1);//true
    }
}

3、String包装类的比较

public class StringDemo {
    //情况1:aStr 与 bString不相同(地址不相同,值是一样的)
        String aStr = "abc";
        String bString = new String("abc");
        System.out.println(aStr == bString);//false
//
        //情况2:创建了3个字符串数组,cStr指向堆内存,cStr1指向堆中的常量池中的某个地址
        String a = "a";
        String b = "b";
        String cStr = a + b;
        String cStr1 = "a" + "b";
        System.out.println(cStr == cStr1);//false

        //情况3:创建了3个字符串数组,cStr指向堆内存,cStr1指向堆中的常量池中的某个地址
        String a1 = "a";
        String b1 = "b";
        String cStr01 = a + b;
        cStr01 = cStr01.intern();
        String cStr11 = "a" + "b";
        System.out.println(cStr01 == cStr11);//true

}

 

4、Integer包装类的比较
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 200;
Integer i4 = 200;
System.out.println(i1 == i2);//true
System.out.println(i3 == i4);//false
通过装箱源码,即valueOf()函数源码看:

@HotSpotIntrinsicCandidate
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的值见如下源码,默认情况下为-128和127

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer[] cache;
    static Integer[] archivedCache;

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                h = Math.max(parseInt(integerCacheHighPropValue), 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

5、Double等其它包装类的比较

 

Double d1 = 1.0;

Double d2 = 1.0;

Double d3 = 2.0;

Double d4 = 2.0;

System.out.println(d1 == d2);//false

System.out.println(d3 == d4);//false

 

查看Double包装类的装箱的源码:

@HotSpotIntrinsicCandidate
public static Double valueOf(double d) {
    return new Double(d);
}

 

IntegerCache.low
posted on 2020-08-23 19:47  风语者未来  阅读(192)  评论(0)    收藏  举报