我一直在研究醉酒的步行者编码问题(自定义用户类等),我要疯了,试图解决这个小问题。
我弄乱了代码(无济于事),所以看不到希望,我决定征求外界意见。
我用来添加到 hashmap 的代码是这样的:
if (hashMap.containsKey(key) == false) {
hashMap.put(key, 1);
}
else {
hashMap.put(key, value + 1);
}
理论上,这应该是完全没问题的。如果 key 没有保存在 map 中,则将其添加到 map 中,值为 1。如果 key 确实存在于 map 中,则 value 加 1。键只是一个带有两个整数变量的自定义类的实例。它正在不断更新。
在程序结束时,如果我在 hashmap 中显示值大于 1 的条目,它应该如下所示:
Visited Intersection [avenue=8, street=42] 3 times!
Visited Intersection [avenue=8, street=63] 2 times!
但是当我观察每个函数调用的 hashmap 是什么样子时,它看起来像这样:
Hash Map: {Intersection [avenue=6, street=22]=1}
Hash Map: {Intersection [avenue=6, street=23]=1, Intersection
[avenue=6, street=23]=1}
Hash Map: {Intersection [avenue=6, street=22]=2, Intersection
[avenue=6, street=22]=1}
Hash Map: {Intersection [avenue=5, street=22]=2, Intersection
[avenue=5, street=22]=1, Intersection [avenue=5, street=22]=1}
Hash Map: {Intersection [avenue=6, street=22]=3, Intersection
[avenue=6, street=22]=1, Intersection [avenue=6, street=22]=1}
...
哈希图中的每个条目都被覆盖,最终产品是这样的:
Visited Intersection [avenue=8, street=20] 3 times!
Visited Intersection [avenue=8, street=20] 2 times!
Visited Intersection [avenue=8, street=20] 2 times!
Visited Intersection [avenue=8, street=20] 2 times!
...
最初我认为添加到 hashmap 的代码是不正确的,因为每个键都被覆盖并且只显示最后更新的一个,但现在我认为它与键的实际更新有关。
一分钱你的想法?对不起,如果它有点模糊。
一只甜甜圈
相关分类