How 'if' syntax in Java works?


  • 0
    J
    List<Integer> stack1 = new ArrayList<>();
    List<Integer> stack2 = new ArrayList<>();
    
    //some add operation
    ......
    //some add operation
    
    if(stack1.remove(index1) == stack2.get(index2-1))
      stack2.remove(--index2);
    

    The code above works wrong.
    While the code below works right.

    List<Integer> stack1 = new ArrayList<>();
    List<Integer> stack2 = new ArrayList<>();
    
    //some add operation
    ......
    //some add operation
    
    int i = stack1.remove(index1);
    int j = stack2.get(index2-1);
    
    if(i == j)
      stack2.remove(--index2);
    

    The former code works that even if the 'if' sentence in latter code judges true, it judges false, which makes me confused.


  • 0
    K

    This is expected behaviour. In first case your comparing two Integer object. For objects, operator == return true only if both the operands is referencing to same object. But for primitive data type it will check if both value is same. For example consider two integer object, Integer test = new Integer(7); Integer test1 = new Integer(7); then test==test1 will return false. As test and test1 is not referencing to same object. You should use equal() or compareTo() method of Integer class in such situation.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.