HashMap源码初探

HashMap源码解读:基于JDK8

类声明:

//HashMap类声明,继承了AbstractMap类、Map接口、Cloneable、Serializable接口
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {}

成员变量:

//底层数组的默认初始化容量,必须是2的幂次方,也就是桶的个数
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//底层数组的最大容量,2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;

//默认哈希表的装载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//当一个桶中数据个数达到该值时,转为红黑树
static final int TREEIFY_THRESHOLD = 8;
//一个树中如果数据个数小于该值,转为链表
static final int UNTREEIFY_THRESHOLD = 6;
//桶中的Node被树化时最小的hash表容量
static final int MIN_TREEIFY_CAPACITY = 64;

//HashMap的底层存储变量
transient Node<K,V>[] table;
//k-v视图窗口,用于快速遍历
transient Set<Map.Entry<K,V>> entrySet;
//HashMap中键值对的数量
transient int size;
/*
 * modCount:记录当前集合被修改的次数
 * (1)添加
 * (2)删除
 * 这两个操作都会影响元素的个数。
 * 
 * 当我们使用迭代器或foreach遍历时,如果你在foreach遍历时,自动调用迭代器的迭代方法,
 * 此时在遍历过程中调用了集合的add,remove方法时,modCount就会改变,
 * 而迭代器记录的modCount是开始迭代之前的,如果两个不一致,就会报异常,
 * 说明有两个线路(线程)同时操作集合。这种操作有风险,为了保证结果的正确性,
 * 避免这样的情况发生,一旦发现modCount与expectedModCount不一致,立即保错。
 * 
 * 此类的 iterator 和 listIterator 方法返回的迭代器是快速失败的:
 * 在创建迭代器之后,除非通过迭代器自身的 remove 或 add 方法从结构上对列表进行修改,
 * 否则在任何时间以任何方式对列表进行修改,
 * 迭代器都会抛出 ConcurrentModificationException。
 * 因此,面对并发的修改,迭代器很快就会完全失败,
 * 而不是冒着在将来某个不确定时间发生任意不确定行为的风险。
 */
transient int modCount;
//表示当size大于threshold时,触发resize方法,扩容的临界值
int threshold;
//哈希表的装载因子,当size/capacity>=loadFactor,触发resize方法
final float loadFactor;

数据主要存储在transient Node<K,V>[] table;中,

遍历时主要使用transient Set<Map.Entry<K,V>> entrySet;

数据存储类

Map.Entry<K,V>接口

interface Entry<K,V> {
        K getKey();

        V getValue();

        V setValue(V value);

        boolean equals(Object o);

        int hashCode();

        public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> c1.getKey().compareTo(c2.getKey());
        }
        public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> c1.getValue().compareTo(c2.getValue());
        }

        public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
            Objects.requireNonNull(cmp);
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
        }

        public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
            Objects.requireNonNull(cmp);
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
        }
    }

Node<K,V>

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

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

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

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

单向链表,HashMap底层是以数组+链表的形式存放数据的

构造方法

按源码中顺序从上到下排列,调用构造方法并没有初始化数组,只是指定了threshold的值,在调用resize方法时,根据threshold来确定capacity的值,即底层数组的大小

构造方法一

//自定义容量和hash因子的构造器
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;
    //通过initialCapacity获取threshold 
    this.threshold = tableSizeFor(initialCapacity);
}

构造方法二

//自定义底层数组大小的构造器
public HashMap(int initialCapacity) {
    //调用了构造方法一
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

构造方法三

public HashMap() {
    //无参构造器,只设置了哈希表的装载因子。
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

构造方法四

//使用一个已有的HashMap创建一个HashMap
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

增–put相关

putMapEntries

//主要使用的地方:putAll方法和构造方法四中,用于批量添加k-v值
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        //新建时,初始化底层数组
        if (table == null) { // pre-size
            //计算capacity
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        //如果放进来的map的键值对大小超过threshold,调用resize方法
        else if (s > threshold)
            resize();
        //遍历map并放到当前map中
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}

put

//新增数据
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

putVal

//新增数据方法
//onlyIfAbsent,是否更新数据,false是更新
//evict,是否创建
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //如果底层数组是null或长度为0,调用resize方法
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    //如果底层数组中索引(n - 1) & hash]上不存在数据,新建节点
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    //节点不为空
    else {
        Node<K,V> e; K k;
        //新增k
        //是否该键值已存在
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        //TreeNode新增
        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
                        //如果一个桶中数据个数超过8,将该节点树化,转为红黑树
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        //添加v
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            //LinkedHashMap使用这里为空方法
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    //是否超过resize的阈值
    if (++size > threshold)
        resize();
    //LinkedHashMap使用这里为空方法
    afterNodeInsertion(evict);
    return null;
}

putAll

//批量添加
public void putAll(Map<? extends K, ? extends V> m) {
    putMapEntries(m, true);
}

删–remove相关

remove

//删除数据
public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

removeNode

final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

clear

//清空数据
public void clear() {
    Node<K,V>[] tab;
    modCount++;
    if ((tab = table) != null && size > 0) {
        size = 0;
        for (int i = 0; i < tab.length; ++i)
            tab[i] = null;
    }
}

查-get相关

get

//返回k对应的v
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

getNode

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    //map不为空,且长度大于0,并且对应的索引(n - 1) & hash上有数据
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        //判断第一个数据是不是要查找的元素,每次都要判断
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        //判断其他数据
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

containsKey

//当前键值对是否有该键
public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

containsValue

//遍历所有数据的值,是否包含value
public boolean containsValue(Object value) {
    Node<K,V>[] tab; V v;
    if ((tab = table) != null && size > 0) {
        for (int i = 0; i < tab.length; ++i) {
            for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                if ((v = e.value) == value ||
                    (value != null && value.equals(v)))
                    return true;
            }
        }
    }
    return false;
}

其他方法

Node<K,V>[] resize()

//调整底层数组大小,新的capacity和threshold为原来的二倍
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    
    //计算新的threshold
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //如果旧的数组长度*2小于最大容量,并且旧的数组长度大于等于默认容量
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            //新的threshold double
            newThr = oldThr << 1; // double threshold
    }
    //当oldTab为null
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    //以带参构造器创建HashMap时
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    //当oldTab为null或者新的数组大小大于MAXIMUM_CAPACITY或旧的数组大小小于DEFAULT_INITIAL_CAPACITY
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    
    threshold = newThr;
    
    //初始化底层数组
    @SuppressWarnings({"rawtypes","unchecked"})
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    //将原来的数据重新分配
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // preserve order
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

size

//返回当前键值对数量
public int size() {
    return size;
}

isEmpty

//当前map是否为空
public boolean isEmpty() {
    return size == 0;
}

其他内部类

  • KeySet: 返回一个视图,包含当前所有键值

  • Values:返回一个视图,包含当前所有value

  • EntrySet:返回一个视图,包含当前所有键值对

其他方法

  • getOrDefault: 根据k获取v,没有改k时,返回默认值
  • putIfAbsent: 当k存在时,不更新已存在的k
  • replace: 使用新的value替换之前的value,如果不存在该k,返回false或null

参考

https://my.oschina.net/architectliuyuanyuan/blog/3089521

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值