测试下面这段代码:
public void test(int x) { Stack<Integer> s1 = new Stack<Integer>(); Stack<Integer> s2 = new Stack<Integer>(); s1.push(x); s2.push(x); int p1 = s1.peek(); int p2 = s2.peek(); System.out.println(p1==p2); System.out.println(s1.peek() == s2.peek()); }如果x在[-128, 127],那么两次都会输出true;如果不是在这个范围,会输出true和false。
原因在于autobox,对于某些值,s1.push(x)会转化为s1.push(Integer.valueOf(x)),然后会利用cache的值,导致实例复用。翻译渣,请参考原解释:
https://stackoverflow.com/questions/31156067/java-stack-peek-behavior
pxy7896 241***7128@qq.com 参考地址