Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entries in a HashMap being overwritten by completely different keys?

Tags:

java

I have a Java HashMap used to store some basic string values:

Map<String, String> map = new HashMap<String, String>();
map.put("Id", task.getStorageId());
map.put("Name", task.getName());
map.put("Description", task.getDescription());

Under one usage, the Id entry is overwitten by the Description entry, everytime without fail. I have watched it in the debugger - Id is inserted fine, Name inserted fine, then when Descroption is inserted, it overwrites the Id entry. Using exactly the same code and keys in another part of the application it works with no problems. Totally confused. What is going on here?

Edit

Perhaps I should have mentioned (though it didn't seem relevant), this is happening on Android, not in a JVM. Could that be the issue? I also found it hard to believe but the chunk of code is as simple as the snippet provided. I will try to bundle an Android app that demonstrates it and post somewhere.

like image 845
MalcomTucker Avatar asked Aug 11 '10 11:08

MalcomTucker


1 Answers

It is likely that the entry you are not seeing is there, look at the modCount for the table and you should see the proper number of entries. This means that a hash collision has occurred. Basically 2 keys got hashed into the same bucket in the table. If you look at the bucket that had the original key it has a next field, which is a pointer to the other entry that you think you have lost.

like image 91
Matt P. Avatar answered Oct 16 '22 08:10

Matt P.