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());
}
4

2 回答 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 ;)

于 2015-07-01T08:22:42.897 回答
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.

于 2015-07-01T08:24:39.460 回答