quick question to be sure I understood well how HashMap in java works.
Here is an example of code:
//String key = new String("key");
//String val = new String("value");
String key = "key";
String val = "value";
HashMap map = new HashMap();
map.put(key, val);
System.out.println("hashmap object created. Its key hashcode = "+key.hashCode());
// the hashcode is 106079
System.out.println("hashmap object value for key = "+map.get(key));
// Let's store using a key with same hashcode
Integer intkey = new Integer(106079);
val = "value2";
map.put(intkey, val);
System.out.println("hashmap object created. Its intkey hashcode = "+intkey.hashCode());
// this returns 106079 once again. So both key and intkey have the same hashcode
// Let's get the values
System.out.println("hashmap object value for intkey = "+map.get(intkey));
System.out.println("hashmap object value for key = "+map.get(key));
the returned values are as expected. I read that behind the scene, HashMap works as follows:
same again for the second one.
To get it:
Am I understanding this concept correctly?
Many thanks!
EDIT:
many thanks, so to complete: - How does Java HashMap store entries internally - How does a Java HashMap handle different objects with the same hash code?
And:
Please also note, there are several ways HashMap can implement hash codes collision resolution, not only utilizing linked list as you mentioned
Java's HashMap implementation does not only use LinkedList
strategy to handle key-values with same key.hashCode()
values.
Also, you may want to read this article
Yes, your understanding is correct. Just note that a single bucket is assigned many hashcodes: in a fresh HashMap
there are altogether 16 buckets, each assigned a total of 232/16 = 228 hashcodes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With