Open Source, Open Future!
  menu
107 文章
ღゝ◡╹)ノ❤️

HashMap

简介

  • JDK1.8之前,底层采用数组+链表的结构;
  • JDK1.8之后,底层采用数组+链表+红黑树的结构;
  • keyvalue都可以为null;
  • 不是线程安全的;

类图

image.png

常量

    // 默认容量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
    // 最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
    // 默认加载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    // 链表转红黑树的阈值(链长度需要大于这个值)
    static final int TREEIFY_THRESHOLD = 8;
    // 链表转红黑树的阈值(容量需要大于这个值)
    static final int MIN_TREEIFY_CAPACITY = 64;
    // 红黑树转链表的阈值
    static final int UNTREEIFY_THRESHOLD = 6;

主要字段

    // 数据全都存在这里
    transient Node<K, V>[] table;
    // entry集合
    transient Set<Map.Entry<K, V>> entrySet;
    // map中存的数据的个数
    transient int size;
    // 修改的次数
    transient int modCount;
    // 扩容阈值(threshold = 容量*加载因子),超出时需要扩容
    int threshold;
    // 加载因子
    final float loadFactor;

构造函数

  • 无参,默认加载因子0.75f
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
  • 指定初始容量initialCapacity
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
  • 指定初始容量和加载因子
    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);
    }

部分API说明

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
	
    // 计算hash值
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
	
    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底层数组为null,或容量为0,则调用resize初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
	// hash计算找到对应的桶,为null则创建链表,将数据保存至头节点
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
	    // 检查头结点,hash值相等且key也相等,e指向头结点
            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) {
		    // 若整个遍历过程都找不到指定的key,则创建新节点
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
			// 若超出了树化阈值,则将链表转换成红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) 
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
			// 找到指定的key,跳出循环
                        break;
                    p = e;
                }
            }
	    // 若经过上面的查询,能找到指定的key,则用新值覆盖旧值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
		// 最后返回旧值
                return oldValue;
            }
        }
        ++modCount;
	// size加 1,若超过扩容阈值,则扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
	// 若是新增操作,则会走到这一步,返回null
        return null;
    }

   public V remove(Object key) {
        Node<K,V> e;
	// 若不能查到指定的key,则返回null;若能查到返回对应的value
        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;
	// hash计算找到对应的桶,桶中数据若为空,直接返回null,否则进行下一步
        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;
	    // 若头结点就是要找的节点,则赋值给node
            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 {
			// 找到指定key,跳出循环
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
			     // 赋值给node
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
	    // 若以上查询能找到指定key
            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);
		// 否则是链表结构,若node是头结点,则使后继节点指向链表头部
                else if (node == p)
                    tab[index] = node.next;
		// 将前驱节点的next指向后驱节点(即将当前节点从链表中移除)
                else
                    p.next = node.next;
                ++modCount;
                // size减 1
                --size;
                afterNodeRemoval(node);
		// 返回当前节点
                return node;
            }
        }
        return null;
    }

    public V get(Object key) {
        Node<K,V> e;
	// 若不能查到指定的key,则返回null;若能查到返回对应的value
        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;
	// hash计算找到对应的桶,桶中数据若为空,直接返回null,否则进行下一步
        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 {
		    // 找到指定key,直接返回
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

示例

测试

备注

使用JDK版本为1.8