Jiyang Liu
Jiyang Liu

Reputation: 1

How 'if' syntax in Java works?

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.

Upvotes: 0

Views: 95

Answers (3)

Dev Blanked
Dev Blanked

Reputation: 8865

In the first case you're using the '==' operator on two Integer objects. That check evaluates to 'true' only if the the two object references point to the same object (same memory location). In the second case you're using '==' operator on two primitive integers. That check evaluates to true if the value of the primitives is the same, even if they reside in different memory locations.

Upvotes: 0

Stanley Xu
Stanley Xu

Reputation: 61

In Java, the == comparator on Object references don't test that the values of the Objects are equivalent. It tests that the references refer to the same Object. In the first case, you're checking if the Integer reference from stack1 and Integer reference from stack2 both refer to the same Integer object.

To test Objects for value equivalence, you generally use the object.equals(otherObject) method.

In the second case, Java does a sneaky thing called autoboxing where it converts an Object to its primitive type, i.e. from Integer to int. The == comparison on primitives is what you'd expect.

See https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html from more info on autoboxing.

Upvotes: 0

Henry
Henry

Reputation: 43728

The stack elements are Integer objects. In the first case you compare them for identity, in the second case you compare the values.

Try this

if(stack1.remove(index1).equals(stack2.get(index2-1)))

Upvotes: 7

Related Questions