cauchy
cauchy

Reputation: 1133

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.

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 HashMap is not equal to the size of vector of costs.

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

I am not able to figure out why.

Upvotes: 1

Views: 19043

Answers (3)

Deepak Banka
Deepak Banka

Reputation: 599

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

Upvotes: 0

Cavallo Nero
Cavallo Nero

Reputation: 26

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.

Upvotes: 0

Eran
Eran

Reputation: 394146

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. 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.

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
}

Upvotes: 2

Related Questions