在 java hashMap 中添加键值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26826014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:41:58  来源:igfitidea点击:

adding a key value pair in java hashMap

javahashmap

提问by cauchy

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.

位置是双精度类型的向量。

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);for all the positions. But there is one problem - the size of HashMapis not equal to the size of vector of costs.

现在我有一个向量,我可以在其中保存所有cost.add(newcost);职位产生的所有成本。但是有一个问题 - 的大小HashMap不等于成本向量的大小。

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

I am not able to figure out why.

我不知道为什么。

采纳答案by Eran

The size of the positionCostMapwon't be the same as the size of the cost Vectorif you are adding the same positionkey more than once to the Map. 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.

的大小positionCostMap不会是相同成本的大小,Vector如果添加相同的position键不止一次到更多Map。在这种情况下,与该键关联的后一个值将覆盖与该键关联的前一个值,并且 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
}

回答by Deepak Banka

This is because size of a hashmap depends on the number of keys.If keys are same,then it will count them as 1.So in your case the hashmap is counting the number of position.Hence the values are different

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

回答by Cavallo Nero

Is it possible that you are adding a position-to-cost mapping to your map multiple times for the same position? I.e. the same Vector object? 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. So I suggest printing the hashcode of the position object you are using as a key to debug.

您是否可能为同一位置多次向地图添加位置到成本的映射?即相同的 Vector 对象?或者也许某些位置对象具有相同的哈希码?这意味着您将在某个时候替换地图中的条目。Vector 对象的行为有所不同 - 它只是附加对象。因此,我建议打印您用作调试键的位置对象的哈希码。