简体   繁体   English

在Java hashMap中添加键值对

[英]adding a key value pair in java hashMap

I have a map which maps cost with position: 我有一张地图,上面标有费用和位置:

Map<Vector<Double>,Double> positionCost=new HashMap<Vector<Double>,Double>();

positions are Vectors of type double. position是类型为double的向量。

I am putting cost for each position by: 我通过以下方式计算每个职位的费用:

positionCost.put(position, newcost);

Now I have a vector where I save all the cost produced cost.add(newcost); 现在我有一个向量,可以保存所有产生的成本cost.add(newcost); for all the positions. 对于所有职位。 But there is one problem - the size of HashMap is not equal to the size of vector of costs. 但是有一个问题HashMap的大小不等于成本向量的大小。

System.out.println("no of particles"+" "+cost.size()+positionCost.size());

I am not able to figure out why. 我不知道为什么。

The size of the positionCost Map won't be the same as the size of the cost Vector if you are adding the same position key more than once to the Map . 如果您多次向Map添加相同的position键,则positionCost Map的大小将与成本Vector的大小不同。 In that case, the latter value associated with that key will overwrite the previous value that was associated that key, and the size of the Map will stay the same. 在这种情况下,与该键关联的后一个值将覆盖与该键关联的前一个值,并且Map的大小将保持不变。

You should add a condition before adding to the map : 您应在添加到地图之前添加条件:

if (!positionCost.containsKey(position)) {
    positionCost.put(position, newcost);
} else {
    // the key already exists in the map. It might be a bug, or it might be 
    // a valid situation that you have to decide how to handle
}

这是因为哈希图的大小取决于键的数量。如果键相同,则将其计为1。因此,在您的情况下,哈希图计算的是位置数。因此值不同

Is it possible that you are adding a position-to-cost mapping to your map multiple times for the same position? 您是否可能为同一位置多次向地图添加位置成本映射? Ie the same Vector object? 即同一个Vector对象? Or perhaps some position objects have the same hashcode? 还是某些位置对象具有相同的哈希码? This will mean that you will replace an entry in your map at some point. 这意味着您将在某个时候替换地图中的条目。 The Vector object behaves differently - it merely appends the object. Vector对象的行为有所不同-它只是追加对象。 So I suggest printing the hashcode of the position object you are using as a key to debug. 因此,我建议打印要用作调试键的位置对象的哈希码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM