HshMap 数据结构以及源码分析

最近整理数据结构方面的知识点,HashMap是很重要的一部分,今天来联合源码分析他的数据结构以及存储方式!
接下来将从以下几个方面来分析(根据JDK1.8)
1. 构造方法
2. 重要的几个数据解释
3. put
4. get

HashMap 的几个重要数据解释

  • HashMap 使用数组+链表进行存储,基本节点形式如下:
// 存储数据的数组 table
transient Node<K,V>[] table;
// 存储数据的基本类型
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;  // 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;
        }
        getter  setter 
  • final float loadFactor; 加载因子
  • int threshold; // 临界值,当大于临界值就扩容
  • transient int modCount; // 当前map对象的修改次数

HshMap的构造方法:

总共有四个构造方法

// initialCapacity:指定Map的容量大小
// loadFactor: 指定加载因子, 默认是DEFAULT_LOAD_FACTOR 0.75
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
    }
// 包含“子Map”的构造函数
public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        // 会如果原始的大小不够,还会进行扩容
        putMapEntries(m, false);,
    }

// 默认的加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;

put

首先来说明下HashMap的数据结构 (图是从别的地方借用的)
这里写图片描述
在HashMap 进行存储数据时,我觉得可以从三点来判断 :
1 . 如何判定key的唯一性
2. 如何通过key计算hash值,并且可以通过hash值计算得到应该放置的数组的位置
3. 什么时候扩容

 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;
        // 首先判断table是否有数据,如果没有就调用resize方法给map分配空间
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 通过  i = (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;
            // 首先判断数组上的存储的key和要存储的key是否相同,如果相同就覆盖
            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 {
            // 接下来,就通过遍历链表,判断key值是否一致
                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;
                } 
            }
            // 对于找到的相同的key的Node,进行value覆盖
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        // map 被修改的次数+1
        ++modCount;
        // 如果长度达到临界值,进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

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

通过上面的代码注释,应该对HashMap的存储方式有更进一步的认识。整个过程就是我们拿到Node的hash值,来计算应该放置的位置,不管value值是Null或者和已经存在的值是否重复,只要找到位置后,放置进去,就OK。

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;
            } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        } else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int) (DEFAULT_LOAD_FACTOR * 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;
    }

resize方法:无非就是重新申请空间,如果一开始是0,就采用和构造方法一样的设置,默认初始大小16;如果之前有数据就成倍增加,并计算新的临界值,重新通过hash值计算在数组中的位置,把之前的数据拷贝到新申请的数组上;数组的扩容是非常耗费性能的,如果我们能提前预算出数组的大小,我们在初始化时可以直接进行指定;

get

首先我们来看源代码,读取数据相对存储数据简单写,我们只需要通过key,判断key的合法性以及通过计算hash 定为元素在数组的位置即可。

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

经过上面的分析,我们知道HashMap主要通过数组+链表的形式存储数据,当存储的数据过多的时候,链表越来越重,之后我们查找起来时间也越来越长,效率越来越低,

JDK 1.8 之后的改进

我们可以看到其中(e instanceof TreeNode) 判断节点是否是TreeNode,JDK1.8中,HashMap采用数组+链表+红黑树来实现,当链表长度超过阈值(8)时,将链表转换为红黑树,这样大大减少了查找时间。

 static final class TreeNode<K, V> extends LinkedHashMap.LinkedHashMapEntry<K, V> {
        TreeNode<K, V> parent;  // red-black tree links
        TreeNode<K, V> left;
        TreeNode<K, V> right;
        TreeNode<K, V> prev;    // needed to unlink next upon deletion
        boolean red;

        TreeNode(int hash, K key, V val, Node<K, V> next) {
            super(hash, key, val, next);
        }
        ...
}

和HashMap相似的HashSet其实就是变形的HashMap,我们可参考这篇文章HashSet简单看下 他们的区别。

参考资料:
https://www.cnblogs.com/ITtangtang/p/3948406.html#a4
https://www.cnblogs.com/skywang12345/p/3310835.html#a22

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值