Inside the get(Object key) method of Java , there is a piece of code which I am not able to understand.
I know how the get(key) method works even in case when hashcode is same for two object.
But the below piece of code I am unable to understand.
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
Can someone explain. Thanks
HashMap
works with Hash bucket algorithm . And Hash buckets are arranged as array which the HashMap
class calls as table
. So the for
loop starts with the first element of the hash bucket which holds the key
Entry<K,V> e = table[indexFor(hash, table.length)
here the hash
represents the hash index of that bucket
for
loop will run till there are elements in the bucket ( e != null
)
for
loop will iterate like e = e.next
, that is, moving to next element in the bucket until match is found
Now, once the hash bucket is found, the method should return the exact Entry whose key matches the passed key
. Now this matching is done by either references matching ( ==
) or equals matching (k = e.key) == key || key.equals(k)
(k = e.key) == key || key.equals(k)
if the matching happens then the key is returned else the method will return null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.