0

In the following code:

HashMap<String, Integer> hm = new HashMap<String, Integer>();
hm.put("Driller", 0);
hm.put("Planner", 1);

"Planner" entry overwrites "Driller". Their respective hashcodes are obviously different. If the keys are just in lowercase ("driller" and "planner") then put works properly. However, for different reasons internal to the project, it is not possible to change the key case.

I am using JDK 7 Update 25 64 bits, but as far as I know String hashcodes have been really stable since early versions.

Do you know what is going on and how could I solve it?

Miguel
  • 11
  • 2

3 Answers3

1

It's not overriding. It's just changing the order of records since you are using hashmap. It automatically sorts by hash value of given string keys. Output your map and see the result.

Mustafa Genç
  • 2,569
  • 19
  • 34
1

Just a comment regarding hashmaps. Even if the hashcodes of the two keys were the same, nothing would get overwritten. The keys would have to be equal with respect to equals method for the value to get overwritten.

Mareen
  • 425
  • 3
  • 5
  • Stating in an answer that it is a comment is bit weird. If you want write a comment then you should do just that. But the content of your "comment" is correct. If you expand it by providing more detail to what the OP is likely seeing then you have a really good answer. – Viktor Seifert Oct 10 '13 at 11:31
0

Mustafa Genç is right.
I commented earlier, but waited to see others answers & finally decided to post with image.
After debugging

HashMap<String, Integer> hm = new HashMap<String, Integer>();
hm.put("Driller", 0);
hm.put("Planner", 1);  

After last statement, hm (HashMap) has two elements with keys, you can see

enter image description here

And

"Driller".hashCode() == "Planner".hashCode()

returns false

Community
  • 1
  • 1
Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90