Comparison between variables pointing to same Integer object

前端 未结 3 871
鱼传尺愫
鱼传尺愫 2020-12-14 08:50

The output of current program is \"Strange\". But both the variables share the same reference. Why are the second and third comparisons not true?

Integer a;
         


        
3条回答
  •  萌比男神i
    2020-12-14 09:51

    • Strage - it's obvious, the two variables point to the same object

    • not Stranger because of autoboxing. Integer is immutable, so each operation on it creates a new instance.

    • not Strangest, because of the previous point, and because you have used new Integer(..) which ignores the cache that is used for the byte range. If you use Integer.valueOf(2) initially, then the cached Integers will be used and Strangest will also be printed.

提交回复
热议问题