Integer value comparison

后端 未结 7 1268
北恋
北恋 2021-02-02 09:31

I\'m a newbie Java coder and I just read a variable of an integer class can be described three different ways in the API. I have the following code:

if (count.         


        
相关标签:
7条回答
  • 2021-02-02 10:22

    One more thing to watch out for is if the second value was another Integer object instead of a literal '0', the '==' operator compares the object pointers and will not auto-unbox.

    ie:

    Integer a = new Integer(0);   
    Integer b = new Integer(0);   
    int c = 0;
    
    boolean isSame_EqOperator = (a==b); //false!
    boolean isSame_EqMethod = (a.equals(b)); //true
    boolean isSame_EqAutoUnbox = ((a==c) && (a.equals(c)); //also true, because of auto-unbox
    
    //Note: for initializing a and b, the Integer constructor 
    // is called explicitly to avoid integer object caching 
    // for the purpose of the example.
    // Calling it explicitly ensures each integer is created 
    // as a separate object as intended.
    // Edited in response to comment by @nolith
    
    0 讨论(0)
提交回复
热议问题