集合框架源码学习之HashMap

这篇博客详细探讨了HashMap的内部工作原理,包括其基于哈希表的存储结构、解决冲突的单链表机制、非线程安全特性以及如何实现序列化和克隆。文章深入分析了HashMap的构造方法、主要方法、Node结构、迭代器以及扩容策略,指出当元素数量超过加载因子与当前容量的乘积时,HashMap会进行扩容到原来的两倍。此外,还介绍了通过特定位运算优化的索引查找方法。
摘要由CSDN通过智能技术生成

简介

  • 基于哈希表,每一个元素都是key-value对,内部通过单链表解决冲突
  • 有闸值,当元素个数大于闸值时会自动扩容(为原来的2倍)
  • 非线程安全
  • 实现了Serializable、Cloneable,支持序列化和克隆

源码

构造方法

public class HashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable {
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16//默认大小:2的4次方
    static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量
    static final float DEFAULT_LOAD_FACTOR = 0.75f;//加载因子,用于控制容量
    transient Node<K,V>[] table;//Node实际为链表,在这里全部链表放在数组里
    int threshold;//闸值,当元素个数达到该值时,容量加倍

    //初始容量大小、加载因子
    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);//获取大于initialCapacity的最小2的次幂,最后获取闸值
    }
    //指定初始化容量的构造函数
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    //默认的构造函数
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
    //传进来集合的构造函数
    public HashMap(Map<? Extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;//设置加载因子
        putMapEntries(m, false);//将map中的元素添加进去
    }
......
}

方法

static final int hash(Object key) {//用key计算hash
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

public V get(Object key) {//根据key获取元素的值,如果元素为null,则返回null
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

final Node<K,V> getNode(int hash, Object key) {//获取元素(Key-Value)
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
//(n – 1) & hash:获取hash在数组的索引,用&是为了提高效率
        (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;//找不到匹配则返回null
}

public  oolean containsKey(Object key) {//是否有存在key 
    return getNode(hash(key), key) != null;
}

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;//如果原数组为null,则初始化一个
    //将hash在数组中索引到的元素赋值给p
if ((p = tab[I = (n – 1) & hash]) == null) //如果链表为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;//如果要插入的元素存在,则p赋值给e
        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) {没有与要插入的key相同,将新元素插进
                    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) { //元素存在,把key对应的Value换成传进来的Value,然后退出
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

public V remove(Object key) {//删除key对应的节点,并返回对应的value
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
//删除指定key对应的元素:找到对应的链表,然后确定是在链头还是中间
    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 {//遍历hash对应的链表
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;//找到对应的元素,退出
                        break;
                    }
                    p = e;//p跟着移动,方便后面的删除
                } 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)//说明key对应的元素是在链头,直接将链头去掉
                tab[index] = node.next;
            else//说明key对应的元素是在链表中间,直接摘断
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;//找不到直接返回null
}

public void clear() {//清空HashMap,将数组中的所有元素都设置为null
   Node<K,V>[] tab;
    modCount++;
    if ((tab = table) != null && size > 0) {
        size = 0;
        for (int I = 0; I < tab.length; ++i)
            tab[i] = null;
    }
}
public boolean containsValue(Object value) {//是否有包含值为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

//Node是一个单向链表
static class Node<K,V> implements Map.Entry<K,V>{
    final int hash;//hash值
        final K key;//节点的key
        V value;//节点的value
        HashMap.Node<K, V> next;//下一个节点

        Node(int var1, K var2, V var3, HashMap.Node<K, V> var4) {
            this.hash = var1;
            this.key = var2;
            this.value = var3;
            this.next = var4;
        }

        public final K getKey() {
            return this.key;
        }

        public final V getValue() {
            return this.value;
        }

        public final String toString() {
            return this.key + "=" + this.value;
        }

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

        public final V setValue(V var1) {
            Object var2 = this.value;
            this.value = var1;
            return var2;
        }

        public final boolean equals(Object var1) {
            if(var1 == this) {
                return true;
            } else {
                if(var1 instanceof Entry) {
                    Entry var2 = (Entry)var1;
                    if(Objects.equals(this.key, var2.getKey()) && Objects.equals(this.value, var2.getValue())) {
                        return true;
                    }
                }

                return false;
            }
        }
}

迭代器

abstract class HashIterator {
    Node<K,V> next;        // 下一个返回的元素
    Node<K,V> current;     // 当前元素
    int expectedModCount;  // 用于fast-fail
    int index;             // 当前的索引

    HashIterator() {
        expectedModCount = modCount;
        Node<K,V>[] t = table;
        current = next = null;
        index = 0;
//找到第一个不为null的元素,并让next指向此元素
        if (t != null && size > 0) { // advance to first entry
            do {} while (index < t.length && (next = t[index++]) == null);
        }
    }

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

    final Node<K,V> nextNode() {
        Node<K,V>[] t;
        Node<K,V> e = next;
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        if (e == null)
            throw new NoSuchElementException();
        if ((next = (current = e).next) == null && (t = table) != null) {//说明当前所在链表已经到尽头了
//让next指向下一个元素,如果当前元素的next为null,则让next指向数组中的下一个不为null的链表头
            do {} while (index < t.length && (next = t[index++]) == null);
        }
        return e;
    }

    public final void remove() {//删除当前元素,不能连续
        Node<K,V> p = current;remove
        if (p == null)
            throw new IllegalStateException();
        if (modCount != expectedModCount)//fast-faild机制
            throw new ConcurrentModificationException();
        current = null;//防止连续两次调用remove方法
        K key = p.key;
        removeNode(hash(key), key, null, false, false);
        expectedModCount = modCount;
    }
}
//key迭代器
final class KeyIterator extends HashIterator
    implements Iterator<K> {
    public final K next() { return nextNode().key; }
}
//值迭代器
final class ValueIterator extends HashIterator
    implements Iterator<V> {
    public final V next() { return nextNode().value; }
}
//元素迭代器
final class EntryIterator extends HashIterator
    implements Iterator<Map.Entry<K,V>> {
    public final Map.Entry<K,V> next() { return nextNode(); }
}

public Set<Map.Entry<K,V>> entrySet() {//获取元素的集合
    Set<Map.Entry<K,V>> es;
    return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
//元素集合
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
    public final int size()                 { return size; }
    public final void clear()               { HashMap.this.clear(); }

    public final Iterator<Map.Entry<K,V>> iterator() {
        return new EntryIterator();
    }
    public final  boolean contains(Object o) {
        if (!(o instanceof Map.Entry))
            return false;
        Map.Entry<?,?> e = (Map.Entry<?,?>) o;
        Object key = e.getKey();
        Node<K,V> candidate = getNode(hash(key), key);
        return candidate != null && candidate.equals(e);
    }
    public final  boolean remove(Object o) {//删除元素
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Object key = e.getKey();
            Object value = e.getValue();
            return removeNode(hash(key), key, value, true, true) != null;
        }
        return false;
    }
 }
 //获取值的集合
 public Collection<V> values() {
    Collection<V> vs = values;
    if (vs == null) {
        vs = new Values();
        values = vs;
    }
    return vs;
}

final class Values extends AbstractCollection<V> {//值的集合
    public final int size()                 { return size; }
    public final void clear()               { HashMap.this.clear(); }
    public final Iterator<V> iterator()     { return new ValueIterator(); }
    public final  oolean contains(Object o) { return containsValue(o); }
 }
 //获取key的集合
public Set<K>  keySet() {
    Set<K> ks =  keySet;
    if (ks == null) {
        ks = new KeySet();
         keySet = ks;
    }
    return ks;
}
//Key的集合
final class KeySet extends AbstractSet<K> {
    public final int size()                 { return size; }
    public final void clear()               { HashMap.this.clear(); }
    public final Iterator<K> iterator()     { return new KeyIterator(); }
    public final  oolean contains(Object o) { return containsKey(o); }
    public final  oolean remove(Object key) {
        return removeNode(hash(key), key, null, false, true) != null;
    }
}

补充

resize():如果原数组为null或者原数组长度小于MAXIMUM_CAPACITY,则重新创建一个新的HshMap并将老的元素全部添加进新的HashMap中。
主要目的是重新调整hashMap的大小,和重新计算hash值。

总结

  • 储存结构:数组(存放表头)、链表(每个节点包含key、value、hash、next),链表用于解决hash冲突,将不同的key映射到同一链表中。
  • 构造函数:有4个,可以指定初始容量(默认16)和加载因子(默认0.75)
  • 当hash表的条目超过(加载因子*当前容量)时,则进行resize(扩容、调整并重新计算hash值)。设置的容量都会是一个不小于我们传进去的容量的2的整数次方。且最大值为2的30次方
  • 使用hash寻找在数组中的索引:(n-1)&hash;这样可以提高效率,n-1是一个奇数,所以用位运算最后一位永远是1,在进行&运算的时候hash值最后一位都是有效,这样可以避免空间的浪费,并且均匀。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值