Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do keys with different hashes also get mapped to the same index in HashMap?

Looking at the code specifically line 393, it looks like different hashes have been mapped to same index. I had an understanding that the hashcode is used to determine what bucket in a HashMap is to be used, and the bucket is made up of a linked list of all the entries with the same hashcode. They why have the e.hash == hash check ?



    public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

like image 598
JavaDeveloper Avatar asked Oct 21 '22 23:10

JavaDeveloper


1 Answers

Since a hashcode can be one in 2^32 values, it is rare that the hashmap has so many buckets (just the table would require 16GB of memory). So yes, you can have objects with different hashes in the same buckets of the maps (AFAIK it is a simple modulus operation of hachCode % numberOfBuckets).

Note that the code does not use directly key.hashCode(), but hash(key.hashCode()).

like image 50
SJuan76 Avatar answered Oct 27 '22 11:10

SJuan76