【问题标题】:Java Stack peek() behaviorJava Stack peek() 行为
【发布时间】:2015-07-01 08:19:06
【问题描述】:

以下代码为除-128 和127 之间的所有值返回false。这有什么特别的原因吗?我知道我必须使用equals,因为peek() 返回对该对象的引用,但我很想知道为什么它只适用于上述值范围。

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

【问题讨论】:

标签: java stack peek


【解决方案1】:

这有两个原因:

当您自动装箱时,某些int x 的s1.push(x) 将转换为s1.push(Integer.valueOf(x))。并且由于这是一个缓存值,因此对于这些值中的任何一个都可以重复使用相同的实例。

根据 JRE 的实现,Integer可能也有比这更大的缓存——但不要依赖它;)

【讨论】:

    【解决方案2】:

    在行中

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

    原语int x 使用Integer.valueOf(x) 自动装箱到Integer 实例中(java 自己会这样做)。该方法使用缓存将Integer 实例存储在-127 到128 的范围内,这意味着对于所有其他int 值,将在上面的两行代码中创建一个新实例,从而导致@987654328 @比较返回false。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      相关资源
      最近更新 更多