Just trying to get my head around the workings of Java HashMap
by looking at the code. When an element is added, the following happens:
- the hashcode for key is got
- a hash function is applied on the result
- the method indexFor is applied on the result of 2. This gives the first entry in the appropriate bucket. The linked list in the bucket is then iterated over - the end is found and the element is added.
The implementation of indexOf is:
int indexOf(int h, int length) {
return h & (length-1);
}
I can't understand the trick going on in the indexOf method. Can anyone explain it?
Thanks.