1

The following code returns false for all values except between -128 and 127. Is there any particular reason for this? I know I have to use equals because peek() returns a reference to the object, but I'm curious to know why it works only for the above range of values.

public boolean test(int x) {
    Stack<Integer> s1 = new Stack<Integer>();
    Stack<Integer> s2 = new Stack<Integer>();
    s1.push(x);
    s2.push(x);
    return (s1.peek() == s2.peek());
}
2

2 Answers 2

4

There are two reasons for this:

When you autobox, s1.push(x) for some int x is transformed into s1.push(Integer.valueOf(x)). And since this is a cached value, the same instance is reused for any of these values.

Depending on the implementation of the JRE, Integer may have a larger cache than that as well -- but don't rely on that ;)

Sign up to request clarification or add additional context in comments.

Comments

0

In the lines

s1.push(x);
s2.push(x);

the primitive int x is autoboxed into an Integer instance using Integer.valueOf(x) (java does that by itself). That method uses a Cache to store Integer instances in the range of -127 to 128, meaning that for all other int values, a new instance will be created in both of the lines of code above, resulting in the == comparison to return false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.