• Post Reply Bookmark Topic Watch Topic
  • New Topic

Trouble with HashMap overwriting wrong key  RSS feed

 
David Erickson
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All:

This is my first post here, so please coach me where I go astray !

In certain situations (not all), I am finding setting key values to the Hashmap (created as a method's local variable , not an instance) will overwrite previously existing keys with different names.

Example:
BEFORE UPDATE
map{"id"= "PO4123123123123"; "name"="My Object"; "number"=123}

map.put("value","New Value");

AFTER UPDATE
map{id"= "PO4123123123123"; "name"="My Object"; "value"="New Value"}

Using debug, I can see where it is replacing table element for "number" in the map with "value". 99% of the time it works as expected; however, I cannot explain or work-around when this issue occurs.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi David,

Interesting! Are the keys really Strings, or are they a user-defined class?
 
David Erickson
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest Friedman-Hill wrote:Hi David,

Interesting! Are the keys really Strings, or are they a user-defined class?


Yes, the keys are strings. Most of the time, it will create a new entry (as expected). The other odd bit - if I do a map.get("value") before the put, it correctly returns null. I thought it might be the .equals, but I am not overriding it in my code and it doesn't get confused on the .get, only on the .put !

Thanks for the reply.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

Please confirm that is always the same Map; if it is a local variable rather than a field you might be creating a new object every time. If you are not sure, try the System#identityHashCode(java.lang.Object) method and see whether you always get the same result.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!