Comparison between variables pointing to same Integer object

前端 未结 3 865
鱼传尺愫
鱼传尺愫 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
    
    0 讨论(0)
  • 2020-12-14 09:41

    An Integer object is immutable, any change in an existing object will create a new object. So after a++, a new object will be created and a will start pointing to that new object while b is still pointing to the old object. Hence, after a++, a and b are pointing to different objects and a == b will always return false.

    with respect to the mentioned example :

    Integer a; //created Integer reference   
    Integer b;  //created Integer reference  
    a = new Integer(2);//created new Integer Object and a reference is assigned to that new object   
    b = a;//b also start pointing to same Integer object   
    if(b == a) { // b==a will be true as both are pointing to same object   
    System.out.println("Strange");   
    }
    a++; //after a++ , a new Integer object will be created (due to Integer immutablity and a will point to that new object while b is still pointing to old), so b==a will be false   
    if(b == a) { 
    System.out.println("Stranger"); 
    }   
    a--; //again a new Integer Object will be created and now a will start pointing to that new Object , so b==a will be false   
    if(b == a) { 
    System.out.println("Strangest");
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题