Forums Register Login

Trouble with HashMap overwriting wrong key

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Hi David,

Interesting! Are the keys really Strings, or are they a user-defined class?
+Pie Number of slices to send: Send
 

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.
+Pie Number of slices to send: Send
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.
This tiny ad is suggesting that maybe she should go play in traffic.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 3436 times.
Similar Threads
Doubt regarding maps key type while bnding
Question from John Meyer's Mock
Help! problem while using logic:iterate with HashMap
Iterating over HaspMap<String,List<Object>> and comparing values.
Problem with ContainsKey(obj key) in HashMap
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 07:27:10.