【问题标题】:GWT emulated indexOf() is incorrect compared to jdk indexOf()与 jdk indexOf() 相比,GWT 模拟 indexOf() 不正确
【发布时间】:2017-11-06 10:16:11
【问题描述】:

由于某种原因,GWT 模拟(客户端)jdk 方法 indexOf() 没有按预期工作。

例子:。

我有一个包含 3 个 NaN 对象的列表:

List<Double> doubleList = new ArrayList<Double>();
doubleList.add(Double.NaN);
doubleList.add(Double.NaN);
doubleList.add(Double.NaN);

我检索最小值,即 Double.NaN:

Double minValue = Collections.min(doubleList); //minValue = Double.NaN

到目前为止,客户端和服务器端的一切都按预期工作。

现在我正在尝试获取 minValue 的索引:

Integer index = doubleList.indexOf(minValue);

这就是乐趣的开始。服务器端(简单单元测试)jdk ArrayList 类方法 indexof() 返回0,应该如此。虽然模拟的 ArrayList 类(客户端)返回不正确的 -1,因为在列表中找不到值时应该返回 -1,这显然不是这种情况。

任何想法为什么会发生这种情况?

GWT indexOf():

  int indexOf(Object o, int index) {
    for (; index < array.length; ++index) {
      if (Objects.equals(o, array[index])) {
        return index;
      }
    }
    return -1;
  }

GWT 模拟 class ArrayList

【问题讨论】:

  • 整数或长列表是否存在同样的问题?
  • @vanje 没有测试过整数/长整数,但我认为不会有任何区别。请注意,这仅适用于 NaN 对象。

标签: java arraylist gwt


【解决方案1】:

In JavaScript NaN === NaN is false 但在 Java 中 Double.NaN.equals(Double.NaN) 是真的。因此,indexOf() 方法中的比较不适用于 NaN。在这种情况下,正确的实现将使用 JavaScript 函数 isNaN()

【讨论】:

  • 这是有道理的,尽管我有点怀疑方法 indexOf() 从 2.7.0 更改为 2.8.2 版本并且 NaN 比较适用于 2.7.0 版本(现在找到 2.7.0 indexOf仿真)
  • 看看两个版本的编译 JavaScript 代码会很有趣。不幸的是,我没有时间做这些事情。
  • 你们可以在 github.com/gwtproject/gwt/issues 提交这个文件以便解决吗?
  • @ColinAlworth 在 github 上注册了这个。
猜你喜欢
  • 1970-01-01
  • 2017-05-18
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多