HashMap源码剖析

2023-05-16

大部分思路都是一样的 ,只是一些细节不一样,源码中都标了出来。jdk容器源码还是挺简单的。

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable
{

  //容量默认值
    static final int DEFAULT_INITIAL_CAPACITY = 16;
//最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

  //装载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

  //数据域
    transient Entry[] table;

  //元素个数
    transient int size;

   //阈值
    int threshold;

  //装在因子
    final float loadFactor;
  //volatile不会再线程私有的地方保留副本,直接写入主存,并且防止JVM重排序
    transient volatile int modCount;

//构造函数
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        //选取比initialCapacity大的最小2的幂次
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;

        this.loadFactor = loadFactor;
        threshold = (int)(capacity * loadFactor);
        table = new Entry[capacity];
        init();
    }

    //构造函数
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

//默认构造函数
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
        table = new Entry[DEFAULT_INITIAL_CAPACITY];
        init();
    }

   
    public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        putAllForCreate(m);
    }
    void init() {
    }

//关键 使hash分布跟均匀  冲突更少
    static int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

   //与hashTable不同这里进行与运算
    static int indexFor(int h, int length) {
        return h & (length-1);
    }

    public int size() {
        return size;
    }


    public boolean isEmpty() {
        return size == 0;
    }

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

    //得到 null key的value
    private V getForNullKey() {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }

    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }
//得到key
    final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key.hashCode());
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
//key相等要 hash和equals同时满足
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }


 
    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<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;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }


    private V putForNullKey(V value) {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }

    private void putForCreate(K key, V value) {
        int hash = (key == null) ? 0 : hash(key.hashCode());
        int i = indexFor(hash, table.length);

        /**
         * Look for preexisting entry for key.  This will never happen for
         * clone or deserialize.  It will only happen for construction if the
         * input Map is a sorted map whose ordering is inconsistent w/ equals.
         */
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                e.value = value;
                return;
            }
        }

        createEntry(hash, key, value, i);
    }

    private void putAllForCreate(Map<? extends K, ? extends V> m) {
        for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
            Map.Entry<? extends K, ? extends V> e = i.next();
            putForCreate(e.getKey(), e.getValue());
        }
    }

//扩容
    void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        Entry[] newTable = new Entry[newCapacity];
        transfer(newTable);
        table = newTable;
        threshold = (int)(newCapacity * loadFactor);
    }
//转移元素
    void transfer(Entry[] newTable) {
        Entry[] src = table;
        int newCapacity = newTable.length;
        for (int j = 0; j < src.length; j++) {
            Entry<K,V> e = src[j];
            if (e != null) {
                src[j] = null;
                do {
                    Entry<K,V> next = e.next;
                    int i = indexFor(e.hash, newCapacity);
                    e.next = newTable[i];
                    newTable[i] = e;
                    e = next;
                } while (e != null);
            }
        }
    }


    public void putAll(Map<? extends K, ? extends V> m) {
        int numKeysToBeAdded = m.size();
        if (numKeysToBeAdded == 0)
            return;

        if (numKeysToBeAdded > threshold) {
            int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
            if (targetCapacity > MAXIMUM_CAPACITY)
                targetCapacity = MAXIMUM_CAPACITY;
            int newCapacity = table.length;
            while (newCapacity < targetCapacity)
                newCapacity <<= 1;
            if (newCapacity > table.length)
                resize(newCapacity);
        }

        for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
            Map.Entry<? extends K, ? extends V> e = i.next();
            put(e.getKey(), e.getValue());
        }
    }


    public V remove(Object key) {
        Entry<K,V> e = removeEntryForKey(key);
        return (e == null ? null : e.value);
    }

    final Entry<K,V> removeEntryForKey(Object key) {
        int hash = (key == null) ? 0 : hash(key.hashCode());
        int i = indexFor(hash, table.length);
        Entry<K,V> prev = table[i];
        Entry<K,V> e = prev;

        while (e != null) {
            Entry<K,V> next = e.next;
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                modCount++;
                size--;
                if (prev == e)
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }

        return e;
    }


    final Entry<K,V> removeMapping(Object o) {
        if (!(o instanceof Map.Entry))
            return null;

        Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
        Object key = entry.getKey();
        int hash = (key == null) ? 0 : hash(key.hashCode());
        int i = indexFor(hash, table.length);
        Entry<K,V> prev = table[i];
        Entry<K,V> e = prev;

        while (e != null) {
            Entry<K,V> next = e.next;
            if (e.hash == hash && e.equals(entry)) {
                modCount++;
                size--;
                if (prev == e)
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }

        return e;
    }


    public void clear() {
        modCount++;
        Entry[] tab = table;
        for (int i = 0; i < tab.length; i++)
            tab[i] = null;
        size = 0;
    }


    public boolean containsValue(Object value) {
	if (value == null)
            return containsNullValue();

	Entry[] tab = table;
        for (int i = 0; i < tab.length ; i++)
            for (Entry e = tab[i] ; e != null ; e = e.next)
                if (value.equals(e.value))
                    return true;
	return false;
    }

    private boolean containsNullValue() {
	Entry[] tab = table;
        for (int i = 0; i < tab.length ; i++)
            for (Entry e = tab[i] ; e != null ; e = e.next)
                if (e.value == null)
                    return true;
	return false;
    }


    public Object clone() {
        HashMap<K,V> result = null;
	try {
	    result = (HashMap<K,V>)super.clone();
	} catch (CloneNotSupportedException e) {
	    // assert false;
	}
        result.table = new Entry[table.length];
        result.entrySet = null;
        result.modCount = 0;
        result.size = 0;
        result.init();
        result.putAllForCreate(this);

        return result;
    }

    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        final int hash;

        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

        public final V setValue(V newValue) {
	    V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

        public final int hashCode() {
            return (key==null   ? 0 : key.hashCode()) ^
                   (value==null ? 0 : value.hashCode());
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }

        /**
         * This method is invoked whenever the value in an entry is
         * overwritten by an invocation of put(k,v) for a key k that's already
         * in the HashMap.
         */
        void recordAccess(HashMap<K,V> m) {
        }

        /**
         * This method is invoked whenever the entry is
         * removed from the table.
         */
        void recordRemoval(HashMap<K,V> m) {
        }
    }

    void addEntry(int hash, K key, V value, int bucketIndex) {
	Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
        if (size++ >= threshold)
            resize(2 * table.length);
    }

 
    void createEntry(int hash, K key, V value, int bucketIndex) {
	Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
        size++;
    }

    private abstract class HashIterator<E> implements Iterator<E> {
        Entry<K,V> next;	// next entry to return
        int expectedModCount;	// For fast-fail
        int index;		// current slot
        Entry<K,V> current;	// current entry

        HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Entry<K,V> nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
	    current = e;
            return e;
        }

        public void remove() {
            if (current == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Object k = current.key;
            current = null;
            HashMap.this.removeEntryForKey(k);
            expectedModCount = modCount;
        }

    }
//直接从 HashIterator的返回值改一下
    private final class ValueIterator extends HashIterator<V> {
        public V next() {
            return nextEntry().value;
        }
    }

    private final class KeyIterator extends HashIterator<K> {
        public K next() {
            return nextEntry().getKey();
        }
    }

    private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
        public Map.Entry<K,V> next() {
            return nextEntry();
        }
    }

    // Subclass overrides these to alter behavior of views' iterator() method
    Iterator<K> newKeyIterator()   {
        return new KeyIterator();
    }
    Iterator<V> newValueIterator()   {
        return new ValueIterator();
    }
    Iterator<Map.Entry<K,V>> newEntryIterator()   {
        return new EntryIterator();
    }


    // Views

    private transient Set<Map.Entry<K,V>> entrySet = null;

    public Set<K> keySet() {
        Set<K> ks = keySet;
        return (ks != null ? ks : (keySet = new KeySet()));
    }

    private final class KeySet extends AbstractSet<K> {
        public Iterator<K> iterator() {
            return newKeyIterator();
        }
        public int size() {
            return size;
        }
        public boolean contains(Object o) {
            return containsKey(o);
        }
        public boolean remove(Object o) {
            return HashMap.this.removeEntryForKey(o) != null;
        }
        public void clear() {
            HashMap.this.clear();
        }
    }


    public Collection<V> values() {
        Collection<V> vs = values;
        return (vs != null ? vs : (values = new Values()));
    }

    private final class Values extends AbstractCollection<V> {
        public Iterator<V> iterator() {
            return newValueIterator();
        }
        public int size() {
            return size;
        }
        public boolean contains(Object o) {
            return containsValue(o);
        }
        public void clear() {
            HashMap.this.clear();
        }
    }

    public Set<Map.Entry<K,V>> entrySet() {
	return entrySet0();
    }

    private Set<Map.Entry<K,V>> entrySet0() {
        Set<Map.Entry<K,V>> es = entrySet;
        return es != null ? es : (entrySet = new EntrySet());
    }

    private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public Iterator<Map.Entry<K,V>> iterator() {
            return newEntryIterator();
        }
        public boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<K,V> e = (Map.Entry<K,V>) o;
            Entry<K,V> candidate = getEntry(e.getKey());
            return candidate != null && candidate.equals(e);
        }
        public boolean remove(Object o) {
            return removeMapping(o) != null;
        }
        public int size() {
            return size;
        }
        public void clear() {
            HashMap.this.clear();
        }
    }
    private void writeObject(java.io.ObjectOutputStream s)
        throws IOException
    {
	Iterator<Map.Entry<K,V>> i =
	    (size > 0) ? entrySet0().iterator() : null;

	// Write out the threshold, loadfactor, and any hidden stuff
	s.defaultWriteObject();

	// Write out number of buckets
	s.writeInt(table.length);

	// Write out size (number of Mappings)
	s.writeInt(size);

        // Write out keys and values (alternating)
	if (i != null) {
	    while (i.hasNext()) {
		Map.Entry<K,V> e = i.next();
		s.writeObject(e.getKey());
		s.writeObject(e.getValue());
	    }
        }
    }

    private static final long serialVersionUID = 362498820763181265L;

    private void readObject(java.io.ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {
	// Read in the threshold, loadfactor, and any hidden stuff
	s.defaultReadObject();

	// Read in number of buckets and allocate the bucket array;
	int numBuckets = s.readInt();
	table = new Entry[numBuckets];

        init();  // Give subclass a chance to do its thing.

	// Read in size (number of Mappings)
	int size = s.readInt();

	// Read the keys and values, and put the mappings in the HashMap
	for (int i=0; i<size; i++) {
	    K key = (K) s.readObject();
	    V value = (V) s.readObject();
	    putForCreate(key, value);
	}
    }

    // These methods are used when serializing HashSets
    int   capacity()     { return table.length; }
    float loadFactor()   { return loadFactor;   }
}

几点总结

    1、首先要清楚HashMap的存储结构,如下图所示:


    图中,紫色部分即代表哈希表,也称为哈希数组,数组的每个元素都是一个单链表的头节点,链表是用来解决冲突的,如果不同的key映射到了数组的同一位置处,就将其放入单链表中。

    2、首先看链表中节点的数据结构:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // Entry是单向链表。    
  2. // 它是 “HashMap链式存储法”对应的链表。    
  3. // 它实现了Map.Entry 接口,即实现getKey(), getValue(), setValue(V value), equals(Object o), hashCode()这些函数    
  4. static class Entry<K,V> implements Map.Entry<K,V> {    
  5.     final K key;    
  6.     V value;    
  7.     // 指向下一个节点    
  8.     Entry<K,V> next;    
  9.     final int hash;    
  10.   
  11.     // 构造函数。    
  12.     // 输入参数包括"哈希值(h)", "键(k)", "值(v)", "下一节点(n)"    
  13.     Entry(int h, K k, V v, Entry<K,V> n) {    
  14.         value = v;    
  15.         next = n;    
  16.         key = k;    
  17.         hash = h;    
  18.     }    
  19.   
  20.     public final K getKey() {    
  21.         return key;    
  22.     }    
  23.   
  24.     public final V getValue() {    
  25.         return value;    
  26.     }    
  27.   
  28.     public final V setValue(V newValue) {    
  29.         V oldValue = value;    
  30.         value = newValue;    
  31.         return oldValue;    
  32.     }    
  33.   
  34.     // 判断两个Entry是否相等    
  35.     // 若两个Entry的“key”和“value”都相等,则返回true。    
  36.     // 否则,返回false    
  37.     public final boolean equals(Object o) {    
  38.         if (!(o instanceof Map.Entry))    
  39.             return false;    
  40.         Map.Entry e = (Map.Entry)o;    
  41.         Object k1 = getKey();    
  42.         Object k2 = e.getKey();    
  43.         if (k1 == k2 || (k1 != null && k1.equals(k2))) {    
  44.             Object v1 = getValue();    
  45.             Object v2 = e.getValue();    
  46.             if (v1 == v2 || (v1 != null && v1.equals(v2)))    
  47.                 return true;    
  48.         }    
  49.         return false;    
  50.     }    
  51.   
  52.     // 实现hashCode()    
  53.     public final int hashCode() {    
  54.         return (key==null   ? 0 : key.hashCode()) ^    
  55.                (value==null ? 0 : value.hashCode());    
  56.     }    
  57.   
  58.     public final String toString() {    
  59.         return getKey() + "=" + getValue();    
  60.     }    
  61.   
  62.     // 当向HashMap中添加元素时,绘调用recordAccess()。    
  63.     // 这里不做任何处理    
  64.     void recordAccess(HashMap<K,V> m) {    
  65.     }    
  66.   
  67.     // 当从HashMap中删除元素时,绘调用recordRemoval()。    
  68.     // 这里不做任何处理    
  69.     void recordRemoval(HashMap<K,V> m) {    
  70.     }    
  71. }    
    它的结构元素除了key、value、hash外,还有next,next指向下一个节点。另外,这里覆写了equals和hashCode方法来保证键值对的独一无二。

    3、HashMap共有四个构造方法。构造方法中提到了两个很重要的参数:初始容量和加载因子。这两个参数是影响HashMap性能的重要参数,其中容量表示哈希表中槽的数量(即哈希数组的长度),初始容量是创建哈希表时的容量(从构造函数中可以看出,如果不指明,则默认为16),加载因子是哈希表在其容量自动增加之前可以达到多满的一种尺度,当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 resize 操作(即扩容)。

    下面说下加载因子,如果加载因子越大,对空间的利用更充分,但是查找效率会降低(链表长度会越来越长);如果加载因子太小,那么表中的数据将过于稀疏(很多空间还没用,就开始扩容了),对空间造成严重浪费。如果我们在构造方法中不指定,则系统默认加载因子为0.75,这是一个比较理想的值,一般情况下我们是无需修改的。

    另外,无论我们指定的容量为多少,构造方法都会将实际容量设为不小于指定容量的2的次方的一个数,且最大值不能超过2的30次方

    4、HashMap中key和value都允许为null。

    5、要重点分析下HashMap中用的最多的两个方法put和get。先从比较简单的get方法着手,源码如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // 获取key对应的value    
  2. public V get(Object key) {    
  3.     if (key == null)    
  4.         return getForNullKey();    
  5.     // 获取key的hash值    
  6.     int hash = hash(key.hashCode());    
  7.     // 在“该hash值对应的链表”上查找“键值等于key”的元素    
  8.     for (Entry<K,V> e = table[indexFor(hash, table.length)];    
  9.          e != null;    
  10.          e = e.next) {    
  11.         Object k;    
  12. /判断key是否相同  
  13.         if (e.hash == hash && ((k = e.key) == key || key.equals(k)))    
  14.             return e.value;    
  15.     }  
  16. 没找到则返回null  
  17.     return null;    
  18. }    
  19.   
  20. // 获取“key为null”的元素的值    
  21. // HashMap将“key为null”的元素存储在table[0]位置,但不一定是该链表的第一个位置!    
  22. private V getForNullKey() {    
  23.     for (Entry<K,V> e = table[0]; e != null; e = e.next) {    
  24.         if (e.key == null)    
  25.             return e.value;    
  26.     }    
  27.     return null;    
  28. }    
    首先,如果key为null,则直接从哈希表的第一个位置table[0]对应的链表上查找。记住,key为null的键值对永远都放在以table[0]为头结点的链表中,当然不一定是存放在头结点table[0]中。

    如果key不为null,则先求的key的hash值,根据hash值找到在table中的索引,在该索引对应的单链表中查找是否有键值对的key与目标key相等,有就返回对应的value,没有则返回null。

    put方法稍微复杂些,代码如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.   // 将“key-value”添加到HashMap中    
  2.   public V put(K key, V value) {    
  3.       // 若“key为null”,则将该键值对添加到table[0]中。    
  4.       if (key == null)    
  5.           return putForNullKey(value);    
  6.       // 若“key不为null”,则计算该key的哈希值,然后将其添加到该哈希值对应的链表中。    
  7.       int hash = hash(key.hashCode());    
  8.       int i = indexFor(hash, table.length);    
  9.       for (Entry<K,V> e = table[i]; e != null; e = e.next) {    
  10.           Object k;    
  11.           // 若“该key”对应的键值对已经存在,则用新的value取代旧的value。然后退出!    
  12.           if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {    
  13.               V oldValue = e.value;    
  14.               e.value = value;    
  15.               e.recordAccess(this);    
  16.               return oldValue;    
  17.           }    
  18.       }    
  19.   
  20.       // 若“该key”对应的键值对不存在,则将“key-value”添加到table中    
  21.       modCount++;  
  22. //将key-value添加到table[i]处  
  23.       addEntry(hash, key, value, i);    
  24.       return null;    
  25.   }   
    如果key为null,则将其添加到table[0]对应的链表中,putForNullKey的源码如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // putForNullKey()的作用是将“key为null”键值对添加到table[0]位置    
  2. private V putForNullKey(V value) {    
  3.     for (Entry<K,V> e = table[0]; e != null; e = e.next) {    
  4.         if (e.key == null) {    
  5.             V oldValue = e.value;    
  6.             e.value = value;    
  7.             e.recordAccess(this);    
  8.             return oldValue;    
  9.         }    
  10.     }    
  11.     // 如果没有存在key为null的键值对,则直接题阿见到table[0]处!    
  12.     modCount++;    
  13.     addEntry(0null, value, 0);    
  14.     return null;    
  15. }   
    如果key不为null,则同样先求出key的hash值,根据hash值得出在table中的索引,而后遍历对应的单链表,如果单链表中存在与目标key相等的键值对,则将新的value覆盖旧的value,比将旧的value返回,如果找不到与目标key相等的键值对,或者该单链表为空,则将该键值对插入到改单链表的头结点位置(每次新插入的节点都是放在头结点的位置),该操作是有addEntry方法实现的,它的源码如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // 新增Entry。将“key-value”插入指定位置,bucketIndex是位置索引。    
  2. void addEntry(int hash, K key, V value, int bucketIndex) {    
  3.     // 保存“bucketIndex”位置的值到“e”中    
  4.     Entry<K,V> e = table[bucketIndex];    
  5.     // 设置“bucketIndex”位置的元素为“新Entry”,    
  6.     // 设置“e”为“新Entry的下一个节点”    
  7.     table[bucketIndex] = new Entry<K,V>(hash, key, value, e);    
  8.     // 若HashMap的实际大小 不小于 “阈值”,则调整HashMap的大小    
  9.     if (size++ >= threshold)    
  10.         resize(2 * table.length);    
  11. }    
    注意这里倒数第三行的构造方法,将key-value键值对赋给table[bucketIndex],并将其next指向元素e,这便将key-value放到了头结点中,并将之前的头结点接在了它的后面。该方法也说明,每次put键值对的时候,总是将新的该键值对放在table[bucketIndex]处(即头结点处)。

    两外注意最后两行代码,每次加入键值对时,都要判断当前已用的槽的数目是否大于等于阀值(容量*加载因子),如果大于等于,则进行扩容,将容量扩为原来容量的2倍。

    6、关于扩容。上面我们看到了扩容的方法,resize方法,它的源码如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // 重新调整HashMap的大小,newCapacity是调整后的单位    
  2. void resize(int newCapacity) {    
  3.     Entry[] oldTable = table;    
  4.     int oldCapacity = oldTable.length;    
  5.     if (oldCapacity == MAXIMUM_CAPACITY) {    
  6.         threshold = Integer.MAX_VALUE;    
  7.         return;    
  8.     }    
  9.   
  10.     // 新建一个HashMap,将“旧HashMap”的全部元素添加到“新HashMap”中,    
  11.     // 然后,将“新HashMap”赋值给“旧HashMap”。    
  12.     Entry[] newTable = new Entry[newCapacity];    
  13.     transfer(newTable);    
  14.     table = newTable;    
  15.     threshold = (int)(newCapacity * loadFactor);    
  16. }    
    很明显,是新建了一个HashMap的底层数组,而后调用transfer方法,将就HashMap的全部元素添加到新的HashMap中(要重新计算元素在新的数组中的索引位置)。transfer方法的源码如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // 将HashMap中的全部元素都添加到newTable中    
  2. void transfer(Entry[] newTable) {    
  3.     Entry[] src = table;    
  4.     int newCapacity = newTable.length;    
  5.     for (int j = 0; j < src.length; j++) {    
  6.         Entry<K,V> e = src[j];    
  7.         if (e != null) {    
  8.             src[j] = null;    
  9.             do {    
  10.                 Entry<K,V> next = e.next;    
  11.                 int i = indexFor(e.hash, newCapacity);    
  12.                 e.next = newTable[i];    
  13.                 newTable[i] = e;    
  14.                 e = next;    
  15.             } while (e != null);    
  16.         }    
  17.     }    
  18. }    
    很明显,扩容是一个相当耗时的操作,因为它需要重新计算这些元素在新的数组中的位置并进行复制处理。因此,我们在用HashMap的时,最好能提前预估下HashMap中元素的个数,这样有助于提高HashMap的性能。

    7、注意containsKey方法和containsValue方法。前者直接可以通过key的哈希值将搜索范围定位到指定索引对应的链表,而后者要对哈希数组的每个链表进行搜索。

    8、我们重点来分析下求hash值和索引值的方法,这两个方法便是HashMap设计的最为核心的部分,二者结合能保证哈希表中的元素尽可能均匀地散列。

    计算哈希值的方法如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static int hash(int h) {  
  2.         h ^= (h >>> 20) ^ (h >>> 12);  
  3.         return h ^ (h >>> 7) ^ (h >>> 4);  
  4.     }  
    它只是一个数学公式,JDK这样设计对hash值的计算,自然有它的好处,至于为什么这样设计,我们这里不去追究,只要明白一点,用的位的操作使hash值的计算效率很高。

    由hash值找到对应索引的方法如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static int indexFor(int h, int length) {  
  2.         return h & (length-1);  
  3.     }  
    这个我们要重点说下,我们一般对哈希表的散列很自然地会想到用hash值对length取模(即除法散列法),Hashtable中也是这样实现的,这种方法基本能保证元素在哈希表中散列的比较均匀,但取模会用到除法运算,效率很低,HashMap中则通过h&(length-1)的方法来代替取模,同样实现了均匀的散列,但效率要高很多,这也是HashMap对Hashtable的一个改进。

    接下来,我们分析下为什么哈希表的容量一定要是2的整数次幂。首先,length为2的整数次幂的话,h&(length-1)就相当于对length取模,这样便保证了散列的均匀,同时也提升了效率;其次,length为2的整数次幂的话,为偶数,这样length-1为奇数,奇数的最后一位是1,这样便保证了h&(length-1)的最后一位可能为0,也可能为1(这取决于h的值),即与后的结果可能为偶数,也可能为奇数,这样便可以保证散列的均匀性,而如果length为奇数的话,很明显length-1为偶数,它的最后一位是0,这样h&(length-1)的最后一位肯定为0,即只能为偶数,这样任何hash值都只会被散列到数组的偶数下标位置上,这便浪费了近一半的空间,因此,length取2的整数次幂,是为了使不同hash值发生碰撞的概率较小,这样就能使元素在哈希表中均匀地散列。






本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HashMap源码剖析 的相关文章

  • 为什么这个 HashMap.get 返回 null?

    我正在尝试创建一个Hashmap为我执行查找 但是 当我运行此测试代码时 输 出为空 我认为这与密钥存储方式的性质有关 但我并不肯定 也许这是一个类似的怪癖 就像var1 var2不等于 除非它们指向内存中的同一个对象 而您必须使用var1
  • Java:HashMap 大小是“质数”还是“2 的幂”?

    许多书籍和教程都说哈希表的大小必须是素数才能将键均匀分布在所有桶中 但是Java的HashMap始终使用 2 的幂的大小 难道不应该使用素数吗 作为哈希表大小 质数 或 2 的幂 哪个更好 使用 2 的幂可以有效地屏蔽哈希码的最高位 因此
  • Json 字符串到地图的转换,

    我正在尝试编写嵌套 JsonObject 到映射转换的通用代码 我有一个示例 JSONObject 作为 glossary title example glossary GlossDiv title S GlossList GlossEnt
  • Java 哈希表与对象引用的问题

    我有一个哈希表 例如 HashTable ht 1 1 2 1 3 1 现在 我像 Integer foo Integer 1 一样实现它 并像这样声明哈希表 HashTable ht foo foo 2 foo 3 foo 现在 据我了解
  • HashMap 分组依据 (Java)

    有没有一种方法可以在Java中按Key分组并将值添加到HashMap中 HashMap
  • Android - 从HashMap中获取值

    我尝试在 Android 中搜索 HashMap 但出现问题 考虑这个例子 HashMap
  • Amazon S3s 密钥背后的数据结构(过滤数据结构)

    我想实现一个类似于 Amazon S3 的查找功能的数据结构 就上下文而言 Amazon S3 将所有文件存储在平面命名空间中 但允许您通过文件名中的公共前缀查找文件组 从而复制目录树的功能 但又不那么复杂 问题是 查找和过滤操作都是 O
  • 根据键名从 HashMap 获取字符串值

    我有一个HashMap有各种键和值 我怎样才能得到一个值 我在地图上有一把钥匙叫my code 它应该包含一个字符串 我怎样才能得到它而不必遍历地图 到目前为止我已经 HashMap newMap new HashMap paramMap
  • Java中如何从HashMap中获取对象

    我试图在给定密钥时从 HashMap 获取测试对象的速度 但我不太确定该怎么做 我尝试过这种方式 但它是错误的 hash values getSpeed 有什么帮助吗 谢谢 class Test private String id priv
  • 如何按整数值对哈希图进行排序[重复]

    这个问题在这里已经有答案了 HashMap
  • Ruby - 将数组映射到哈希图

    我有一个数组和一个返回给定值的函数 最终我想创建一个哈希映射 将数组的值作为键值 将 f key value 的结果作为值 是否有一种干净 简单的方法 例如类似于数组的each map 使用块来执行此操作 所以相当于 hsh 1 2 3 4
  • 以 null 为键的 HashMap

    How HashMap内部区分null and 0作为关键 按照这个post https stackoverflow com questions 17268212 hashcode for null key in hashmap的哈希码nu
  • 如何将数据存储在对象的对象列表中?

    我有以下代码 将年龄相同且得分最高的用户分组 我现在有而不是Map
  • 如何将 HashMap> 存储在列表中?

    我的哈希图将字符串存储为键 将数组列表存储为值 现在 我需要将其嵌入到列表中 也就是说 它将采用以下形式 List
  • ANSI C 哈希表实现,数据位于一个内存块中

    我正在寻找一种哈希表的开源 C 实现 它将所有数据保存在一个内存块中 因此可以轻松地通过网络发送数据 我只能找到为添加到其中的每个键值对分配小块内存的内存 预先非常感谢您的所有投入 编辑 它不一定需要是哈希表 无论键值对表可能会做什么 序列
  • Java - 线程“主”中的异常 java.util.ConcurrentModificationException

    有什么办法可以修改HashMap迭代特定键时的值 下面给出一个示例程序 public static void main String args HashMap
  • equals 和 hashcode 的不同字段

    我同意这篇文章的声明在Java中重写equals和hashCode时应该考虑哪些问题 https stackoverflow com questions 27581 overriding equals and hashcode in jav
  • 同步不经常更新的哈希图的最佳方式

    我有一个在应用程序中使用的 HashMap 数据是在应用程序初始加载期间从数据库填充的 然后它始终只是读取并且从不更新 会有多个线程不断地读取数据 由于数据永远不会更新 因此我们目前不使用任何同步 仅使用 HashMap 我们现在定义的方式
  • Java 弱哈希映射 - 需要根据值的弱点而不是键来删除条目

    所以JavaWeakHashMap让我们创建一个映射 如果其键变弱 则删除该映射的条目 但是我怎样才能创建一个Map 当它的条目被删除时values地图上变弱了 我想使用映射的原因是作为全局哈希表 它根据对象的 ID 跟踪对象 ID gt
  • JSON 中的哈希到底是什么?

    我正在学习 JSON 但我发现你也可以将所谓的 哈希 放入 JSON 中 我在哪里可以找到什么是哈希 或者你能向我解释一下什么是哈希吗 另外 什么是哈希图 我有 C 和 C 经验 正在学习 JS Jquery 和 JSON 哈希是一个稀疏数

随机推荐