Java中的`Map.containsKey(ArrayList)`在一行中返回false,在下一行中返回true。

huangapple go评论74阅读模式
英文:

Java Map.containsKey(ArrayList) returns false in one line and true in the next

问题

我有一个 HashMap<ArrayList<Integer>, Integer>。在替换这些对象之前,我会从映射中删除对象,所以我试图避免对已经存在键的 put 调用,以保持映射的大小不变(这是我从头开始编写的稳态进化算法)。

替换是从一个 ArrayList<ArrayList<Integer>> listOfArrs 中进行的。在我的一些运行中,映射的大小有所减少,因为这个嵌套的 ArrayList 中存在重复项。在调试过程中,我发现了这个问题:下面的代码会打印出 GOODBYE,但不会打印出 HELLO

void updateMap(ArrayList<ArrayList<Integer>> listOfArrs) {
    // 调试循环
    for (ArrayList<Integer> arr : listOfArrs) {
        if (mapObj.containsKey(arr)) System.out.println("HELLO");
    }
    for (ArrayList<Integer> arr : listOfArrs) {
        if (mapObj.containsKey(arr)) System.out.println("GOODBYE");
        mapObj.put(arr, 0);
    }
}

当我最初从另一个函数中获得 listOfArrs 时,我尝试使用 listOfArrs.removeIf(arr -> mapObj.containsKey(arr)) 来防止重复项,但似乎这并没有起作用。

英文:

I have a HashMap&lt;ArrayList&lt;Integer&gt;, Integer&gt;. I'm removing objects from the Map before replacing them, so I'm trying to avoid put calls which already have the key present in order to keep the Map size the same (for a steady-state Evolutionary Algorithm I'm writing from scratch).

The replacements are coming from an ArrayList&lt;ArrayList&lt;Integer&gt;&gt; listOfArrs. Throughout some of my runs, the Map size has been decreasing because there have been duplicates present in this nested ArrayList. In the course of debugging, I've found this problem: the following code prints GOODBYE but not HELLO.

void updateMap(ArrayList&lt;ArrayList&lt;Integer&gt;&gt; listOfArrs) {
    //debug loop
    for (ArrayList&lt;Integer&gt; arr : listOfArrs) {
        if (mapObj.containsKey(arr)) System.out.println(&quot;HELLO&quot;);
    }
    for (ArrayList&lt;Integer&gt; arr : listOfArrs) {
        if (mapObj.containsKey(arr)) System.out.println(&quot;GOODBYE&quot;);
        mapObj.put(arr, 0);
    }
}

When I originally get the listOfArrs from a different function, I use listOfArrs.removeIf(arr -&gt; mapObj.containsKey(arr)) in an attempt to prevent duplicates, but it seems that's not working.

答案1

得分: 2

弄清楚了 - 这是一个明显的问题。listOfArrs 包含了我没有检查到的重复项。当我在原始帖子中迭代那个第二个 for 循环时,它们开始出现,因为我是在添加了第一个重复项之后才检查映射。

英文:

Figured it out - it's an obvious one. The listOfArrs contained duplicates that I didn't check for. When I'm iterating through that second for loop in the original post they start showing up because I'm checking the map after I've added one of the first duplicates.

huangapple
  • 本文由 发表于 2020年9月25日 05:46:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64054873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定