如何修复 HashMap 更新每个现有值而不是单个值

我一直在研究醉酒的步行者编码问题(自定义用户类等),我要疯了,试图解决这个小问题。


我弄乱了代码(无济于事),所以看不到希望,我决定征求外界意见。


我用来添加到 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 的代码是不正确的,因为每个键都被覆盖并且只显示最后更新的一个,但现在我认为它与键的实际更新有关。


一分钱你的想法?对不起,如果它有点模糊。


摇曳的蔷薇
浏览 145回答 1
1回答

一只甜甜圈

哈希图中的每个条目都被覆盖...我怀疑你不太明白它是如何HashMap工作的。 HashMap存储对非副本的引用。key我怀疑您在Intersection将其放入地图后会覆盖其中的字段。这是一个非常糟糕的模式,可能会导致一些非常奇怪的结果。有几件事要检查。你应该new Intersection(avenue, street)每次都做。考虑在您的Intersectionbe中创建 2 个字段final。这始终是一个很好的模式,因此您不会无意中更改键的值。确定其中一个或两个字段是否是“身份”字段,它应该是final.您需要确保Intersection对象具有正确识别每个值的适当方法hashcode()。equals()否则,每个Intersection都将存储在地图中,无论它们是否具有相同的avenue和street值。在这里查看我的答案:https ://stackoverflow.com/a/9739583/179850您应该从地图中获取交叉点的计数,然后增加该值。也许是这样的:Intersection key = new Intersection(8, 42);...Integer count = hashMap.get(key);if (count == null) {   hashMap.put(key, 1);} else {   hashMap.put(key, value + 1);}...public class Intersection {   // these fields can't be changed   private final int avenue;   private final int street;   ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java