HashMap的介绍和源码解析

2018-08-29  本文已影响0人  high5130

HashMap的介绍

1、HashMap的简介

基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。
2、HashMap的构造函数

//构造一个带指定初始容量和默认加载因子 (0.75) 的空 HashMap
public HashMap(int initialCapacity) 
//构造一个具有默认初始容量 (16) 和默认加载因子 (0.75) 的空 HashMap
public HashMap() 
//构造一个映射关系与指定 Map 相同的新 HashMap
public HashMap(Map<? extends K, ? extends V> m)
//构造一个带指定初始容量和加载因子的空 HashMap
public HashMap(int initialCapacity, float loadFactor) 

HashMap的数据结构

HashMap的重要字段说明

    //创建 HashMap 时未指定初始容量情况下的默认容量   
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 

   //HashMap 的最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //HashMap 默认的装载因子,当 HashMap 中元素数量超过 容量*装载因子 时,进行 resize() 操作
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //用来确定何时将解决 hash 冲突的链表转变为红黑树
    static final int TREEIFY_THRESHOLD = 8;

    // 用来确定何时将解决 hash 冲突的红黑树转变为链表
    static final int UNTREEIFY_THRESHOLD = 6;
 
    /* 当需要将解决 hash 冲突的链表转变为红黑树时,需要判断下此时数组容量,
    若是由于数组容量太小(小于 MIN_TREEIFY_CAPACITY )导致的 hash 冲突太多,
    则不进行链表转变为红黑树操作,转为利用 resize() 函数对 hashMap 扩容 */
    static final int MIN_TREEIFY_CAPACITY = 64;

HashMap的重要方法和源码解析

HashMap就是一个散列表,它是通过“拉链法”解决哈希冲突的,影响HashMap性能的有两个参数:初始容量(initialCapacity) 和加载因子(loadFactor)。容量 是哈希表中桶的数量,初始容量只是哈希表在创建时的容量。加载因子 是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数。

//HashMap的数据存储是Node类型的数组,Hash的键值对是存储在Node中的,从下面的结构可以看出,//Node其实就是一个单项列表,
//Node实现了Map.Entry 接口,即实现getKey(), getValue(), setValue(V value), equals(Object o), hashCode(这些函数。
//这些都是基本的读取/修改key、value值的函数。
static class Node<K,V> implements Map.Entry<K,V> {
        final int 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;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
//插入数据
//往HashMap中传入数据
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);  //获取键的hash值 调用添加
    }

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)  //如果当前map中没有数据 对数组进行初始化操作
            n = (tab = resize()).length;   
        if ((p = tab[i = (n - 1) & hash]) == null)    //通过数组长度和hash找到的索引位置没有数据 则直接添加到找到的索引位置
            tab[i] = newNode(hash, key, value, null);   //把新创建的Node赋值到索引位置上
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))  //判断当前位置上 key是否相同
                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  如果桶里面的数据超过了TREEIFY_THRESHOLD值,就把这个桶从链表结构变成红黑树结构
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))  //链表上key相同 
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key  //是否key相同
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)   //onlyIfAbsent 如果为true则不修改key的位置的value值 否则替换成新的value值
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)   //size大于HashMap的阈值 对数组大小进行自增
            resize();
        afterNodeInsertion(evict);   //用于LinkedHashMap 回调函数
        return null;
    }

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) {    //当前容量大于最大数组容量 就把阈值设置为Integer的最大值 数组不在进行自增
                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  //默认阈值大于0 ,在带参创建的时候会产生这种情况
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);  //否则按HashMap自带的默认参数构建新的数组和阈值的大小
        }
        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) {  //如果当前node中数组 则把数据填充到新的数组里面
          // 根据容量进行循环整个数组,将非空元素进行复制
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                // 获取数组的第j个元素
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)   //如果链表只有一个数据 则直接按Hash的算法进行赋值
                        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;
    }

public void putAll(Map<? extends K, ? extends V> m) {   //添加一组Map数据到HashMap中来
        putMapEntries(m, true);
    }

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()) {   //循环调用putVal添加数据
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }
//获取数据
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) {  //符合条件判断   first = tab[(n - 1) & hash]) != null判断这个位置是否存在数据
            if (first.hash == hash && // always check first node  //如果当前first就是查询的数据直接返回
                ((k = first.key) == key || (key != null && key.equals(k)))) 
                return first;
            if ((e = first.next) != null) {  //如果first链表下面有数据 
                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;
    }
//删除数据
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) {    //通过key查询到数组下标位置 取出链表
            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 {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            } 
            //上面为查出数据 
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) { //数据判断是否需要匹配value
                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;
    }

HashMap的遍历方式

//entrySet方式遍历
Iterator<Map.Entry<String,String>> iter = map.entrySet().iterator();
        while (iter.hasNext()){
           Map.Entry<String,String> entry =  iter.next();
           String key = entry.getKey();
           String value = entry.getValue();
        }
//KeySet方式遍历
Iterator<String> iter = map.keySet().iterator();
        while (iter.hasNext()){
           String key  =  iter.next();
           String value = map.get(key);
        }
//value遍历
Iterator<String> iter = map.values().iterator();
        while (iter.hasNext()){
           String value  =  iter.next();
        }

推荐使用第一种方式

上一篇 下一篇

猜你喜欢

热点阅读