[整理] Integer 常量池 (Java)

public class Main {
    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));
    }
}

你们可以先思考一下再往下翻看答案,看看能不能做对。

解题思路

在解这道题之前,相信很多人都已经知道了,在Java中会有一个Integer缓存池,缓存的大小是:-128~127

答案是:

  • true
  • false
  • true
  • true
  • true
  • false
  • true

简单解释一下:

  • 使用==的情况:

    • 如果比较Integer变量,默认比较的是地址值。
    • Java的Integer维护了从-128~127的缓存池
    • 如果比较的某一边有操作表达式(例如a+b),那么比较的是具体数值
  • 使用equals()的情况:

    • 无论是Integer还是Long中的equals()默认比较的是数值。
    • Long的equals()方法,JDK的默认实现:会判断是否是Long类型
  • 注意自动拆箱,自动装箱问题。

posted @ 2020-12-21 20:49  哆啦梦乐园  阅读(125)  评论(0编辑  收藏  举报