Java中的HashMap

HashMap是基于Map接口实现的,用于存储键值对的集合

特点

  1. 元素是无序的:元素位置是根据hash值和数组长度位运算得到的,无法保证元素的插入顺序
  2. 键不允许重复,值允许重复:map中的key是不允许重复的,value允许重复
  3. 键值都允许null值:key和value都允许null值
  4. hash冲突:键根据hash值和数组长度计算出来的索引位可能会重复,出现hash冲突,此时冲突的键值对会以链表的形式存储
  5. 链表过长会转化为红黑树:当链表长度到达8且数组长度大于64时,链表会转化为红黑树
  6. 非线程安全:HashMap不支持多线程

底层原理

  • HashMap的底层数据结构是基于动态数组+链表+红黑树
  • 数组的初始容量为16,在首次往数组中放入元素时初始化
  • 当数组中的元素个数大于数组容量的75%时,数组扩容到原数组容量的2倍
  • 冲突的键值对以链表的形式存储(在冲突的索引位形成链表)
  • 当链表长度大于8且数组长度小于64时,数组会进行扩容,扩容后原数组元素将重新计算索引位存储
  • 当链表长度大于8且数组长度大于64时,链表会转化为红黑树
  • 若红黑树的节点个数减少到6时,会退化为链表
  1. 链表长度大于8时,不会立即转化为红黑树,是因为后续数组如果要扩容,会拆分红黑树分布到新的数组中,会降低性能
  2. 红黑树的节点个数小于6时退化为链表,是因为在链表个数少时,查询效率已经足够。且维护红黑树需要占用更多的内存,计算节点也更耗性能

 方法(部分)

构造方法
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    //实际存储元素的数组
    transient Node<K,V>[] table;

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

    //实际元素个数
    transient int size;

    //map修改次数
    transient int modCount;

    //数组扩容的临界值
    int threshold;

    //负载因子
    final float loadFactor;

    //创建一个HashMap,自定义初始化容量和负载因子
    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);
    }

    //创建一个HashMap,自定义初始化容量,默认负载因子为0.75
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    //创建一个HashMap,默认初始化容量为16,负载因子为0.75
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    //创建一个HashMap,负载因子默认0.75,将传入数组元素复制到新数组
    //(新创建Node存放键值对,若键值对是引用类型,可能会出现修改m会影响HashMap的值)
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

构造函数中,传入参数是Map集合,若map集合中的value是引用类型,可能会出现修改其中一个集合中的value值,会影响到另一个集合

HashMap<String, User> map = new HashMap<>( 10 );

HashMap<String, User> map2 = new HashMap<>( map );

user对象中的属性值,map或者map2其中一个集合进行了修改,会影响另一个

还有一种情况,若value值的类型是String,那么map或者map2对原键值对中的value进行修改,并不会影响其中一个(字符串对象每次修改实际都是创建了一个新的对象)

 添加单个元素
    //添加单个元素
    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;
        //如果是初次使用map,对数组进行扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果通过元素key的hash值和数组长度位运算计算出来的索引位没有元素,则将元素放入此索引位
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //如果计算出来的索引位已经有值了
        else {
            Node<K,V> e; K k;
            //并且此索引位的key和传入的key是相同的,将索引位的节点p复制给变量e
            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) {
                    //如果遍历到链表尾端没有找到属于key的键值对,则在尾端添加一个元素
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //链表长度大于8了,调用treeifyBin判断是扩容数组还是树化链表
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果找到了key相同的键值对,获取当前的键值对元素e
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //单次逻辑结束,将当前e复制给p,以便下一次链表遍历判断
                    p = e;
                }
            }
            //此时的e是map中已经存在的键值对元素,将新的value值更新到e节点中
            if (e != null) { 
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //添加完元素后超过map扩容临界值,进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
添加多个元素
    public void putAll(Map<? extends K, ? extends V> m) {
        putMapEntries(m, true);
    }

    //计算当前数组是否需要扩容,若需要则扩容,扩容后遍历传入的map集合,插入键值对
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            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);
            }
        }
    }
有条件添加单个元素
    //键值对不存在的时候添加元素
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }
根据key删除单个元素
    public V remove(Object key) {
        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) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        //删除的大前提:map集合不为空并且通过key的hash值和数组长度位运算后的索引位不为空
        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;
            //如果当前索引位元素的key和传入的key相同(hash和内容都相同),需要删除的node就是p
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            //如果当前索引位元素的key和传入的key不同,且p有下一个节点关联
            else if ((e = p.next) != null) {
                //如果是数结构,遍历数找到对应的节点
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                //如果是链表,遍历链表找到和传入的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);
                }
            }
            //查找到了需要删除的节点,并根据条件判断是否要比对value值
            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;
                //如果是链表,将需要删除的node节点的前一个节点的next指向node的next
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }
根据key-value删除元素
    //删除键值对能匹配上的元素节点
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }
获取元素
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        //大前提:map不为空并且根据key的hash值和数组长度位运算得出的索引位有元素
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //如果索引位元素的key和传入的key相同(hash值和内容都相同),返回索引位元素
            if (first.hash == hash && 
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //如果索引位元素不是要查找的,且存在hash冲突的链表或者红黑树
            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;
    }
forEach遍历
    
    public void forEach(BiConsumer<? super K, ? super V> action) {
        Node<K,V>[] tab;
        if (action == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            //数组循环中,遍历单个索引位(如果存在链表或者树结构)
            for (Node<K,V> e : tab) {
                for (; e != null; e = e.next)
                    action.accept(e.key, e.value);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }
 computeIfAbsent

如果集合中指定key的节点中已经有value值,则不做任何操作直接返回

如果集合中指定key的节点没有value值(null),则将value值放入节点中

如果集合中不存在指定key的节点,则创建新的节点放入数组(hash冲突则添加到链表或者红黑树)

    public V computeIfAbsent(K key,
                             Function<? super K, ? extends V> mappingFunction) {
        if (mappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node<K,V>[] tab; Node<K,V> first; int n, i;
        int binCount = 0;
        TreeNode<K,V> t = null;
        Node<K,V> old = null;
        //第一次向集合中添加元素,扩容
        if (size > threshold || (tab = table) == null ||
            (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果根据key的hash值和数组长度位运算得到的索引位有元素
        if ((first = tab[i = (n - 1) & hash]) != null) {
            //是树结构中的元素,遍历树找到指定key对应的节点
            if (first instanceof TreeNode)
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
            //根据索引位遍历链表,查找key对应的节点
            else {
                Node<K,V> e = first; K k;
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
            V oldValue;
            //如果查找到的节点value已经有值了,直接返回旧值,不做任何运算
            if (old != null && (oldValue = old.value) != null) {
                afterNodeAccess(old);
                return oldValue;
            }
        }
        int mc = modCount;
        //调用传入的函数进行value值运算
        V v = mappingFunction.apply(key);
        if (mc != modCount) { throw new ConcurrentModificationException(); }
        //计算出来的值为null,直接返回;
        if (v == null) {
            return null;
        } 
        //如果是Node节点,将value值设置到节点;
        else if (old != null) {
            old.value = v;
            afterNodeAccess(old);
            return v;
        }
        //如果是树节点,调用putTreeVal设置value值
        else if (t != null)
            t.putTreeVal(this, tab, hash, key, v);
        //如果key在集合中不存在,则创建一个新节点放入索引位或者链表头
        else {
            tab[i] = newNode(hash, key, v, first);
            if (binCount >= TREEIFY_THRESHOLD - 1)
                treeifyBin(tab, hash);
        }
        modCount = mc + 1;
        ++size;
        afterNodeInsertion(true);
        return v;
    }
 扩容
final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        //如果原数组容量已经达到数组最大容量,则不扩容
        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)
                newThr = oldThr << 1; // double threshold
        }
        //如果旧容量等于0并且旧的临界值大于0,说明在创建集合时指定了临界值,
        //则将临界值作为新数组容量
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        //旧容量和旧的临界值都是0,则使用默认的初始化容量和临界值
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        //如果新的临界值为0,则计算新的临界值
        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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值