HashMap的put方法(Java7)和putVal方法(Java8)

数组+链表:存在性能最坏情况O(n)

Java8以前,HashMap底层数据结构采用数组+链表的结构。
数组特点:查询快,增删慢。
链表特点:查询慢,增删较快。
HashMap:结合了数组和链表的优势。同时HashMap的操作是非Synchronized,因此效率比较高。

Java7的HashMap的put方法思路

put源码:

public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        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;
    }

addEntry源码:

/**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
     * method to resize the table if appropriate.
     *
     * Subclass overrides this to alter the behavior of put method.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

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

方法简述:
1、初始化HashMap,若Entry数组类型的table为空,inflated(膨胀,扩容意思)一个table,threshold默认=初始容量=16;
2、对key求Hash值,然后再计算table下标;
3、如果没有碰撞,即数组中没有相应的键值对,直接放入桶(bucket)中,如果碰撞了,以链表的方式链接到后面;
4、如果键值对已经存在就替换旧值;
5、如果桶满了(容量16*加载因子0.75),就需要扩容resize();

但是,存在坏情况:如果通过哈希散列运算得到的是同一个值,即总是分配到同一个桶中,使某个桶的链表长度很长。
由于链表查询需要从头开始遍历,最坏情况下,HashMap性能变为O(n)。

数组+链表+红黑树:性能提高到O(logn)

Java8以后,HashMap底层数据结构采用数组+链表+红黑树的结构。
通过常量TREEIFY_THRESHOLD=8和UNTREEIFY_THRESHOLD=6来控制链表与红黑树的转化。

Java8的HashMap的putVal方法思路

putVal源码:

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

在Java7源码基础上增加了链表和红黑树的转化。
如果链表长度超过阈值8,就把链表转换成红黑树,如果链表长度低于6,就把红黑树转回链表。改变了最坏情况下O(n),性能提高到O(logn)。
注意:Java7中数组里的元素叫Entry,Java8及以后改名为Node(节点)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值