Why is there a difference in the HashMap and Hastable methods?

I was interested to know the difference of methods putin HashMapandHashtable

Hashtable enter method code

Entry tab[] = table;
     int hash = key.hashCode();
     int index = (hash & 0x7FFFFFFF) % tab.length;
     for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
         if ((e.hash == hash) && e.key.equals(key)) {
             V old = e.value;
             e.value = value;
             return old;
         }
     }

HashMap enter method code

int hash = hash(key.hashCode());
     int i = indexFor(hash, table.length);
     for (Entry<K,V> 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;
         }
     }

why hashtable has different code for index search?

int index = (hash & 0x7FFFFFFF) % tab.length;

while hashMap has a hash()function provided by jdk constructors.

+4
source share
2 answers

What is 0x7FFFFFFFbinary format? That 01111111111111111111111111111111.

, 0. , ( ). - & , & -ed , , :

01111111111111111111111111111111
Anything                          &
--------------------------------
0 ← Always

% , tab.length.

, HashMap . , . , .

HashMap indexFor, : return h & (length-1);

: HashTable HashMap, , .

0

HashTable:

int index = (hash & 0x7FFFFFFF) % tab.length;

: - ()

HashMap:

int i = indexFor(hash, table.length);

:

static int indexFor(int h, int length) {
   return h & (length-1);
}

-1 , modulo length-1 , , , - -2. -1 , , 0xFFFFFFFF, , , 0xFFFFFFFE.

( HashMap HashTable). (), . hash(), (. ) HashTable:

int hash = hash(key.hashCode());

hash():

           /**
  258      * Applies a supplemental hash function to a given hashCode, which
  259      * defends against poor quality hash functions.  This is critical
  260      * because HashMap uses power-of-two length hash tables, that
  261      * otherwise encounter collisions for hashCodes that do not differ
  262      * in lower bits. Note: Null keys always map to hash 0, thus index 0.
  263      */
  264     static int hash(int h) {
  265         // This function ensures that hashCodes that differ only by
  266         // constant multiples at each bit position have a bounded
  267         // number of collisions (approximately 8 at default load factor).
  268         h ^= (h >>> 20) ^ (h >>> 12);
  269         return h ^ (h >>> 7) ^ (h >>> 4);
  270     }
  271 
0

All Articles