• Post Reply Bookmark Topic Watch Topic
  • New Topic

HashMap key behavior for wrapper objects  RSS feed

 
Greenhorn
Posts: 9
Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi folks,
I am trying to understand the working of HashMap. Here is a simple example
hm.put(1, "a");
hm.put(1, "b");
hm.put(4000, "c");
hm.put(new Integer(4000), "d");

When I try to print the final output, I get => {1=b, 4000=d}

My question is aren't 4000 and new Integer(4000) unequal and therefore the hashmap should have 3 values => {1=b, 4000=c, 4000=d}
Thanks!
 
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Objsooj Ram wrote:Hi folks,
I am trying to understand the working of HashMap. Here is a simple example
hm.put(1, "a");
hm.put(1, "b");
hm.put(4000, "c");
hm.put(new Integer(4000), "d");

When I try to print the final output, I get => {1=b, 4000=d}

My question is aren't 4000 and new Integer(4000) unequal and therefore the hashmap should have 3 values => {1=b, 4000=c, 4000=d}
Thanks!


If the boxed version of 4000 and new Integer(4000) were unequal as far as .equals() was concerned, then the wrapper classes would not be very useful.

HashMap will do what all good equality comparison code does when checking objects for equality: it uses the .equals() method, not ==. And 4000.equals(new Integer(4000)) better return true.
 
Objsooj Ram
Greenhorn
Posts: 9
Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Steve,
Thank you for opening my eyes, I was thinking about the Object class equals() method when I posted the doubt and totally overlooked that Integer class overrides it where it checks for value equivalence and not == as in Object method. Therefore couldnt understand the output :-)

thanks!!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!