常用集合之HashMap源码浅析

类图

源码

构造方法

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    //无参构造函数时使用该 负载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //最大容量十进制值为 1073741824  
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //The next size value at which to resize (容量capacity * 负载因子loadfactor)
    int threshold;

    //保存数据的数组
    transient Node<K,V>[] table;

    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);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }



}

数据结构

如下是节点的数据结构,由源码可知是一个单向链表:

 static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next; //下一个节点,即子节点

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        //...     
    }

Node数据结构和数据源table可知HashMap是一个数组,而数组的每一个节点,又可以分支为一个一个的单向链表。由此可以得到HashMap数据结构的以下模型:

put方法

···

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

···
可见,经过了一顿复杂的算法。总结起来就像是下面这样:

首先会将传入的 Keyhash运算计算出 hashcode,然后根据数组长度取模计算出在数组中的index下标。
由于在计算中位运算比取模运算效率高的多,所以 HashMap规定数组的长度为2^n。这样用 2^n - 1 做位运算与取模效果一致,并且效率还要高出许多。
由于数组的长度有限,所以难免会出现不同的Key通过运算得到的index相同,这种情况可以利用链表来解决,HashMap 会在table[index]处形成链表,采用头插法将数据插入到链表中。

get方法

getput类似,也是将传入的Key 计算出 index ,如果该位置上是一个链表就需要遍历整个链表,通过 key.equals(k) 来找到对应的元素。就不细说了。

遍历方式

 Iterator<Map.Entry<String, Integer>> entryIterator = map.entrySet().iterator();
 while (entryIterator.hasNext()) {
     Map.Entry<String, Integer> next = entryIterator.next();
     System.out.println("key=" + next.getKey() + " value=" + next.getValue());
 }
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()){
    String key = iterator.next();
    System.out.println("key=" + key + " value=" + map.get(key));
}
map.forEach((key,value)->{
    System.out.println("key=" + key + " value=" + value);
});

强烈建议使用第一种 EntrySet 进行遍历。

第一种可以把 key value 同时取出,第二种还得需要通过key 取一次 value,效率较低, 第三种需要 JDK1.8以上,通过外层遍历 table,内层遍历链表或红黑树。

猜你喜欢

转载自blog.csdn.net/She_lock/article/details/81778956
今日推荐