Why aren't Integers cached in Java?

前端 未结 15 1606
無奈伤痛
無奈伤痛 2020-11-27 05:27

I know there are similar posts on the topic, but they don\'t quite address my question. When you do:

Integer a = 10;
Integer b = 10;
System.out.println(\"a =         


        
15条回答
  •  执念已碎
    2020-11-27 05:53

    BTW, If you do

    Integer a = 234345;
    Integer b = 234345;
    
    if (a == b) {}
    

    it is possible that this will be true.

    This is because since you didn't use new Integer(), the JVM (not the class code) is allowed to cache its own copies of Integers if it sees fit. Now you shouldn't write code based on this, but when you say new Integer(234345) you are guaranteed by the spec that you will definitely have different objects.

提交回复
热议问题