No, this is no bug and has nothing to do with Stack
and all to do with the Integer
class. Understand that Integer is a reference type and so two Integers can be .equal(...)
and not ==
. Understand that when used on reference types ==
checks if the two object references are the same which is not what you're interested in. The equals(...)
method on the other hand checks if the values held by the two Integer objects are the same, and that's what matters here. This is similar to the situation we have with checking for String equality.
If you did:
// convert Integers to ints and test for primitive equality:
System.out.println((s.peek().intValue() == ss.peek().intValue()));
// or test using the equals(...) method
System.out.println((s.peek().equals(ss.peek())));
// or test with Integer#compareTo:
System.out.println((s.peek().compareTo(ss.peek()) == 0));
you'd get:
true
true
true
Note also this interesting question: Why does 128==128 return false but 127==127 return true in this code?. The answers explain why the check for equal references (i.e. ==
on reference types) on Integer
variables returns true
for a certain range of integer literals, like in this example:
System.out.println((Integer) 1024 == (Integer) 1024);
System.out.println((Integer) 127 == (Integer) 127);
prints:
false
true