Why aren't Integers cached in Java?

前端 未结 15 1622
無奈伤痛
無奈伤痛 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:55

    It is my understanding that new will create a new object, no matter what. The order of operations here is that you first call new, which instantiates a new object, then the constructor gets called. There is no place for the JVM to intervene and turn the new into a "grab a cached Integer object based on the value passed into the constructor".

    Btw, have you considered Integer.valueOf? That works.

提交回复
热议问题