I meet a really strang problem using Java Stack.
Stack<Integer> s=new Stack(), ss=new Stack();
s.push(1024); ss.push(1024);
System.out.println(s.peek());
System.out.println(ss.peek());
System.out.println((s.peek()==ss.peek()));
System.out.println((s.peek()<ss.peek()));
System.out.println((s.peek()<=ss.peek()));
System.out.println((s.peek()!=ss.peek()));
See above code. But why the output is like this??
1024
1024
false
false
true
true
Is this a bug in Java?? Some one help.... Thanks, Kai
No, this is no bug and has nothing to do with
Stack
and all to do with theInteger
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. Theequals(...)
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:
you'd get:
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) onInteger
variables returnstrue
for a certain range of integer literals, like in this example:prints: