Hashmap

一、HashMap简介

HashMap是基于哈希表的Map接口实现,采用key-value形式存储,其中key是可以允许为null但是只能是一个,并且key不允许重复(如果重复则新值覆盖旧值)。在结构上,HashMap 是由数组+链表+红黑树构成。在添加元素时,通过计算来确定该元素放入的位置,理想状态下时均匀的放入数组中,但如果发生冲突时,即索引位置相同时,如果两者相等则直接覆盖,如果不同则产生了新的结构——链表,冲突的元素会在该索引处以链表的形式保存,但是当链表的长度过长时,查询效率较低,就引出了第三种数据结构——红黑树,远远比链表的查询效率高,链表的节点超过8则会转红黑树,当链表的值小于6则会从红黑树转回链表。

构造函数中,两个参数分别是初始容量initialCapacity(默认为 16)和负载因子loadFactor(默认为0.75f),

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;
    //threshold 表示下次需要扩容时的容纳最大值, 如果超出这个值, 则会进行扩容
  
this.threshold = tableSizeFor(initialCapacity); }

二、主要方法

2.1 put()方法

   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;
    //将当前 hashmap 中的 table(哈希表)赋值给tab,判断tab 是不是为空
if ((tab = table) == null || (n = tab.length) == 0)
    //如果是空的需要创建新的哈希表,默认创建一个长度为 16 的哈希表 n = (tab = resize()).length;
    //(n - 1) & hash])就是找当前要插入的数据应该在哈希表中的位置,找到插入位置的节点p,如果空的,则直接插入 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else {//插入位置冲突 Node<K,V> e; K k;
        //如果当前位置上的那个数据的 hash 和要插入的 hash 是一样,代表没有放错位置 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
        //将当前节点赋值为e 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);
               //链表长度大于8时,将链表转红黑树 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后移 p = e; } }
        //如果当前的节点等于空则说明上面的遍历到了最后,并且是新建节点完成添加
        //如果不为空,代表上面链表中存在key相同的节点,需要替换 if (e != null) { // existing mapping for key
         //将当前节点的值赋值给 oldvalue V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
 

2.2 resize()方法

扩容,HashMap初始化后首次插入数据时,先发生resize扩容再插入数据,之后每当插入的数据个数达到threshold时就会发生resize,此时是先插入数据再resize,如果已经扩容过的话,那么每次table的容量以及threshold量为原有的两倍。做了两步工作, 一步是计算新的阈值和容量, 一步是键值对重新映射。

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) {//table扩容过 // 如果数组长度达到最大值,修改临界值 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } // 如果当前hash桶数组的长度在扩容后仍然小于最大容量 并且oldCap大于默认值16 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; // 当阈值==0的时候 else { //默认构造器下进行扩容 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]; // 将旧tab中的Node转移到新tab中, 分链表和红黑树两种情况 table = newTab; if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) {//如果旧的hash桶数组在j结点处不为空,复制给e oldTab[j] = null;//将旧的hash桶数组在j结点处设置为空, if (e.next == null) newTab[e.hash & (newCap - 1)] = e;//直接对e的hash值对新的数组长度求模获得存储位置 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; }

2.3 remove()方法

   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;
        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 {
            //遍历链表 do {
               //hash值相等,并且key地址相等 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; }
              //p保存当前遍历到的节点 p = e; } 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)
            //要删除的是头节点 tab[index] = node.next; else
            //将当前节点指向删除节点的下一个节点 p.next = node.next; ++modCount; --size; afterNodeRemoval(node); return node; } } return null; }

2.4 getNode()方法

final Node<K,V> getNode(Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & (hash = hash(key))]) != null) {
       //判断该数组索引位置处第一个是否为我们要找的元素 判断条件需要满足hash 和 key 相同
            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;
    }

2.5 containsValue()方法

外层循环遍历table数组,内层循环遍历链表数据,一旦查找到相同的value就返回true,否则就返回false。

    public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        if ((tab = table) != null && size > 0) {
            for (Node<K,V> e : tab) {
                for (; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

  

方法

posted @ 2021-09-10 13:30  zq231  阅读(96)  评论(0)    收藏  举报