Java之Integer封装与拆箱

132 阅读1分钟
public class Demo {
    public static void main(String[] args) {
        Integer a = 1000, b = 1000;
        Integer c = 100, d = 100;
        int e = 100;
        Integer f = new Integer(10);
        Integer g = new Integer(10);

        System.out.println(a == b);// false
        System.out.println(c == d);// true
        System.out.println(e == d);// true
        System.out.println(f == g);// false
    }
}

编译后:

public class Demo {
  public static void main(String[] args) {
    Integer a = Integer.valueOf(1000);Integer b = Integer.valueOf(1000);
    Integer c = Integer.valueOf(100);Integer d = Integer.valueOf(100);
    int e = 100;
    Integer f = new Integer(10);
    Integer g = new Integer(10);
    
    System.out.println(a == b);
    System.out.println(c == d);
    System.out.println(e == d.intValue());
    System.out.println(f == g);
  }
}

其中的奥秘:

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

当我们声明一个Integer c = 100;的时候,此时会进行自动装箱操作。简单点说,也就是把基本数据类型转换成Integer对象,而转换成Integer对象正是调用的valueOf方法,可以看到,Integer中把-128至127 缓存了下来。

当Integer对象是new出来的,并不是用的缓存,所以结果是false。