HashMap学习笔记整理

HashMap

Hashmap实现了Map,克隆,序列化接口,因为没有加锁,所以是一个线程不安全的容器。底层使用了数组+链表,JDK8以后增加了红黑树这种数据结构。

内部使用的节点

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
}

static final class TreeNode<K,V> extends LinkedHashMap.Entry<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);
        }
}
需要注意的地方
  • 节点实现了Map.Entry接口
  • 除了key,value,还有指向下一个节点的指针以及hash值
  • hsah和key值被final修饰(所以hash值和key相同,两个就是相同的节点)
  • 当数组长度大于64,链表长度大于8时会变为红黑树(因为小于64时,直接搜索速度更快些,红黑树的变色以及左旋右旋操作会开销时间)
  • 存取是无序的
  • key可以为null,因为源码中在putVal时专门处理了键值为null的情况,开辟一个新的节点并存放在第一位(面试)

为什么采用数组+链表+红黑树

  • 如果采用arraylist中按顺序摆放的结构,插入比较方便,但是查询非常不方便,因为Key值大部分时候并不是数字下标,如果通过遍历来查询效率极低,所以不适用按顺序存放。
  • 为了提高查询的效率,Hashmap通过key值的hash值决定数据的存放问题。相同的key值可以得到相同的index
  • 如果产生了hash冲突,就使用链表来解决hash冲突(在同一位置挂一个链表垂下来,是不是很像葫芦娃,hhh)
  • 当链表过长时,将链表变为红黑树,链表平均O(n/2),树的复杂度为(log2n)

存储过程

  1. 根据key值计算出hash值
  2. 根据hash值计算出桶内位置(&操作与%操作结果相同,但是处理速度极快)
  3. 如果该位置没有元素,直接插入
  4. 如果有元素,链表插入(更新),红黑树插入(更新)
  5. 如果是链表,且元素长度大于8,若数组长度大于64,变红黑树,如果数组长度小于64.扩容
  6. 如果元素大于阈值(数组长度*因子),进行扩容。

Hashmap中的成员变量以及方法

1.DEFAULT_INITIAL_CAPACITY 默认初始化大小16

/**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

2.Hashmap数组最大长度

 /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

问题一:为什么数组长度一定是2次幂

  • 首先我们应该记住,jdk任何设计的最终目的一定因为可以提高效率,或者可读性
  • hashmap使用哈希值确定下标,为了减少hash碰撞,因此要尽可能的平均分配hsah散列
  • 使用哈希值确定下标时,需要对哈希值取余数组长度,但是&运算显然比%更快捷(涉及到计算机底层,位运算一定是快于普通运算)
  • 为了将算法简化,也就是达到 hash&length-1==hash%length 的效果,因此对length的要求就是必须为2^n
2的n次幂就是首位为1,后面全是0
2的n次幂-1就是首位为0,后面全是1

2^n  1000 0000
2^-1 0111 1111

假设hash值为2和3(一般是32位处理),length为8,

hash 3      0000 0011
length-1 7  0000 0111
index    3  0000 0011

hash 2      0000 0010
length-1 7  0000 0111
index    2  0000 0010

假设hash值为2和3(一般是32位处理),length为9,不为2的n次幂

hash 3      0000 0011
length-1 8  0000 1000
index    0  0000 0000

hash 2      0000 0010
length-1 8  0000 1000
index    0  0000 0000

2的n次-1可以保证最高位为0,所以&操作后产生结果不会大于length
也就保证了下标的正确性,(或和亦或都会产生错误)

除了最高的,剩下都是1,这就可以使hash值的后几位不变  

问题二:如果初始化时传入的值不是2的n次幂,会如何转为2的n次幂

会自动转换为最小的刚好比传入值大的2的n次幂(比如给15,返回16),因为初始化时会调用一个方法进行处理

static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
cap=9--> 0000 1001
tip:>>>是无符号的右移,>>是有符号右移,区别是高位补0还是补1

n     0000 1001
n>>>1 0000 0100
n     0000 1101

n     0000 1101
n>>>2 0000 0011
n     0000 1111


n     0000 1111
n>>>4 0000 0000
n     0000 1111

-------------------------------
可以看到,在进行一系列的右移操作后,最终会得到一个各位全是1的数字
这是数字就是cap所在的二次幂区间的最大值(例如9介于8和16之间,这个最大值就是15)
最后返回n+1,就可以获得结果

tip:n为什么是cap-1,如果cap刚好是2的n次幂的话,那么就会得到比他大一轮的n次幂
例如传入16,会返回32,因此先-1,在+1,就可以保证结果正确

3.默认负载因子

(加载因子过大会导致hash冲突严重,链表过长,查询效率降低,加载因子过小会导致数组稀疏,空间利用率低)

 /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

4.大于8会变为红黑树,小于6变回链表

 /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

问题:为什么大于8变为红黑树

回答一:根据泊松分布,链表大于8的几率已经很小了
回答二:log(8)=3,6/2=3,所以6和8刚好是树和链表复杂度曲线同一高度时的情况

5.size记录元素个数,modCount记录操作数

    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     */
    transient int modCount;

增加方法

image

// 入参 hash:通过 hash 算法计算出来的值。
static final int hash(Object key) {
    int h;
    //通过高低位互相亦或来解决冲突问题,只看低位会造成重复
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

// 入参 onlyIfAbsent:false 表示即使 key 已经存在了,仍然会用新值覆盖原来的值,默认为 false
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    // n 表示数组的长度,i 为数组索引下标,p 为 i 下标位置的 Node 值
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //如果数组为空,使用 resize 方法初始化
    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);
    // 如果当前索引位置有值的处理方法,即我们常说的如何解决 hash 冲突
    else {
        // e 当前节点的临时变量
        Node<K,V> e; K k;
        // 如果 key 的 hash 和值都相等,直接把当前下标位置的 Node 值赋值给临时变量
        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) {
                // e = p.next 表示从头开始,遍历链表
                // p.next == null 表明 p 是链表的尾节点
                if ((e = p.next) == null) {
                    // 把新节点放到链表的尾部 
                    p.next = newNode(hash, key, value, null);
                    // 当链表的长度大于等于 8 时,链表转红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1)
                        treeifyBin(tab, hash);
                    break;
                }
                // 链表遍历过程中,发现有元素和新增的元素相等,结束循环
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                //更改循环的当前元素,使 p 在遍历过程中,一直往后移动。
                p = e;
            }
        }
        // 说明新节点的新增位置已经找到了
        if (e != null) {
            V oldValue = e.value;
            // 当 onlyIfAbsent 为 false 时,才会覆盖值 
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            // 返回老值
            return oldValue;
        }
    }
    // 记录 HashMap 的数据结构发生了变化
    ++modCount;
    //如果 HashMap 的实际大小大于扩容的门槛,开始扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

扩容机制

当需要扩容时,将数组大小扩大一倍,将原先数组中的数据重新进行分配,降低密度。

数组中元素的新位置等于老位置或老位置+扩容size
如果第n位是1,则新位置=老位置+扩容size
如果第n位是0,则新位置=老位置

hash 值14 0000 1110
hash 值18 0001 0010
原来是lenght=16,扩容后=32

hash值 14
原数组位置
0000 1110
0000 1111
0000 1110 14

扩容后数组位置

0000 1110
0001 1111
0000 1110 14

hash值 18
原数组位置
0001 0010
0000 1111
0000 0010 2

扩容后数组位置
0001 0010
0001 1111
0001 0010 18

扩容机制源码

  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;
            }
            //如果再扩大一炮也没有超过上限,可以扩容,赋值给newThr
            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;
                //不为null,则进行复制,否则跳过
                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;
                            //注意之前取余是hash&length-1,这里直接hash&length,可以得到第n位是0,还是1,0则保持原位,1则原位+扩容size
                            //此处通过判断结果是0还是1,维护出两条新链表
                            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;
    }

删除方法

 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;
            //如果相等,将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 {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            //如果node不为空,说明找到了这个点
            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;
    }

查询方法

    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的几种方式

 class Foo {
    public static void main(String[] args) {
        HashMap<String,Integer>map=new HashMap<>();
        for(int i=1;i<=3;i++){
            map.put(i+""+i,i);
        }
        //method1(map);
        //method2(map);
        //method3(map);
        //method4(map);
        
    }
    //jdk8以后实现了foreach接口
    private static void method4(HashMap<String, Integer> map) {
        map.forEach((Key, Value)->{
            System.out.println("key: "+Key+" value: "+Value);
        });
    }
    //jdk8以后实现了foreach接口
    private static void method3(HashMap<String, Integer> map) {
        for(Map.Entry<String, Integer> entry: map.entrySet())
        {
            System.out.println("Key: "+ entry.getKey()+ " Value: "+entry.getValue());
        }
    }
    
    private static void method2(HashMap<String, Integer> map) {
        //获取entrySet
        Iterator it=map.entrySet().iterator();
        //遍历
        while (it.hasNext()){
            //此处需要强转
            System.out.println(((Map.Entry<String, Integer>)it.next()).getKey());
        }
    }

    public static void method1(HashMap<String,Integer>map){
        //获取所有key
        Set<String>set=map.keySet();
        for(String key:set)
            System.out.println(key);
        //获取所有values
        Collection<Integer>values=map.values();
        for(Integer value:values)
            System.out.println(value);
    }
}

猜你喜欢

转载自www.cnblogs.com/wjune-0405/p/12762675.html