Integer梳理

Integer常量池

问题1
public class Main_1 {
    public static void main(String[] args) {
        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        Long h = 2L;
        System.out.println(c == d);
        System.out.println(e == f);
        System.out.println(c == (a + b));
        System.out.println(c.equals(a + b));
        System.out.println(g == (a + b));
        System.out.println(g.equals(a + b));
        System.out.println(g.equals(a + h));
    }

}

// 结果
true
false
true
true
true
false
true
问题2
public class Main {
    public static void main(String[] args) {
         
        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 200;
        Integer i4 = 200;
         
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}


//结果
true
false
问题3
public class Main {
    public static void main(String[] args) {
         
        Double i1 = 100.0;
        Double i2 = 100.0;
        Double i3 = 200.0;
        Double i4 = 200.0;
         
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}
//结果
false
false
解释
  • 使用==的情况:
    如果比较Integer变量,默认比较的是地址值。
    Java的Integer维护了从-128~127的缓存池
    如果比较的某一边有操作表达式(例如a+b),那么比较的是具体数值

  • 使用equals()的情况:
    无论是Integer还是Long中的equals()默认比较的是数值。
    Long的equals()方法,JDK的默认实现:会判断是否是Long类型

  • a+b包含了算术运算,因此会触发自动拆箱过程

  • Integer常量池

    • Integer中有个静态内部类IntegerCache,里面有个cache[],也就是Integer常量池,常量池的大小为一个字节(-128~127)。
    • 当创建Integer对象时,不使用new Integer(int i)语句,大小在-128~127之间,对象存放在Integer常量池中。
    • 当超过这个范围后会重新实例化
    • 大部分包装类型都有这个机制
    • Integer的valueOf方法源码

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

  • 为什么Double类的valueOf方法会采用与Integer类的valueOf方法不同的实现。很简单:在某个范围内的整型数值的个数是有限的,而浮点数却不是。

    • Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。
    • Double、Float的valueOf方法的实现是类似的。
自动装箱与拆箱
  • 装箱就是自动将基本数据类型转换为包装器类型;拆箱就是自动将包装器类型转换为基本数据类型。
 //自动装箱
 Integer total = 99;
 
 //自定拆箱
 int totalprim = total;
原文地址:https://www.cnblogs.com/frankltf/p/10375177.html