How does Java implement hash tables?

前端 未结 5 1822
甜味超标
甜味超标 2020-12-14 03:55

Does anyone know how Java implements its hash tables (HashSet or HashMap)? Given the various types of objects that one may want to put in a hash table, it seems very difficu

5条回答
  •  长情又很酷
    2020-12-14 04:09

    In my own words:

    An Entry object is created to hold the reference of the Key and Value.

    The HashMap has an array of Entry's.

    The index for the given entry is the hash returned by key.hashCode()

    If there is a collision ( two keys gave the same index ) , the entry is stored in the .next attribute of the existing entry.

    That's how two objects with the same hash could be stored into the collection.

    From this answer we get:

       public V get(Object key) {
           if (key == null)
               return getForNullKey();
           int hash = hash(key.hashCode());
           for (Entry 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;
           }
           return null;
       }
    

    Let me know if I got something wrong.

提交回复
热议问题