Have I found a bug in Java Stack class? Why this two stack element is not the same??

105 views Asked by At

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

1

There are 1 answers

2
Hovercraft Full Of Eels On

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