Comparison between variables pointing to same Integer object

前端 未结 3 868
鱼传尺愫
鱼传尺愫 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条回答
  •  执笔经年
    2020-12-14 09:40

    That's the artifact of autoboxing and a fact that Integer is immutable in Java.

    The a++ and a-- are translated to roughly this.

    int intA = a.getInt( );
    intA++;
    a = Integer.valueOf( intA ); // this is a reference different from b
    

提交回复
热议问题