Internals of how the HashMap put() and get() methods work (basic logic only )

后端 未结 3 1848
面向向阳花
面向向阳花 2020-12-06 07:48

When we put a key instance say \"key\" and a Value instance say \"value\" in a HashMap class using put() method , what does the HashMap

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 08:08

    This is what is done in IBM jdk 1.6 (i believe it is pretty much the same for all vendors)

    EDIT

    Regarding equals and hashcode you might be interested in seeing this post.

    END of EDIT

     /**
     * Maps the specified key to the specified value.
     * 
     * @param key
     *            the key
     * @param value
     *            the value
     * @return the value of any previous mapping with the specified key or null
     *         if there was no mapping
     */
    @Override
    public V put(K key, V value) {
        return putImpl(key, value);
    }
    
    V putImpl(K key, V value) {
        Entry entry;
        if(key == null) {
            entry = findNullKeyEntry();
            if (entry == null) {
                modCount++;
                if (++elementCount > threshold) {
                    rehash();
                }
                entry = createHashedEntry(null, 0, 0);
            }
        } else {
            int hash = key.hashCode();
            int index = hash & (elementData.length - 1);
            entry = findNonNullKeyEntry(key, index, hash);
            if (entry == null) {
                modCount++;
                if (++elementCount > threshold) {
                    rehash();
                    index = hash & (elementData.length - 1);
                }
                entry = createHashedEntry(key, index, hash);
            }
            if ((cache != null) && (hash >> CACHE_BIT_SIZE == 0)
                    && (key instanceof Integer)) {
                cache[hash] = value;
            }
        }
    
        V result = entry.value;
        entry.value = value;
        return result;
    }
    

提交回复
热议问题