英文:
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<ArrayList<Integer>, Integer>
. 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<ArrayList<Integer>> 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<ArrayList<Integer>> listOfArrs) {
//debug loop
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);
}
}
When I originally get the listOfArrs
from a different function, I use listOfArrs.removeIf(arr -> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论