1 回答
TA贡献1836条经验 获得超5个赞
哈希图中的每个条目都被覆盖...
我怀疑你不太明白它是如何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;
...
添加回答
举报
