数据结构与算法之从哈希表到HashMap(二)

HashMap的基本结构


HashMap是基于哈希表的键值对存储类,它通过将键值对包装成Entry,然后根据键的hash值确定保存的位置。下面我们先看HashMap里几个重要的类与变量。

Entry类
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里的数据都会被封装成这个类的对象,可以看到他是一个单链表,在HashMap里,同一个链表里面保存的Node的键的哈希值是相同的,也就是说这个链表是为了解决hash冲突的。

数据保存的对象
transient Node<K,V>[] table;

HashMap的数据就是保存在这个数组里,而数组的每一个位置都对应着一个哈希函数的值,而每个位置存放着一个链表,个类的对象,可以看到他是一个单链表,在HashMap里,同一个链表里面保存的Node的键的哈希值是相同的。

容量和加载因子
int threshold;//容量

final float loadFactor;//加载因子

这两个参数是来度量当前的HashMap是否需要扩容的,有如下算式:

threshold=槽位数(也就是table.length)x loadFactor;

可以看到loadFactor是是final的,也就是对于一个HashMap对象,其的加载因子是确定且不可改变的的。加载因子的默认值是0.75,也就是说在默认情况下,当table数组长度为16时,链表最多保存12个键值对。

HashMap的put与get

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;
    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);
    else {
        Node<K,V> e; K k;
        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) {
                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;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

将数据放到HashMap里面,会先调用函数计算出哈希值

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

注意,这个函数的返回值不是哈希表概念下的哈希值,而是(n - 1) & hash,其中n是当前table数组的长度,由于数组的长度一定是2的指数,所以相当于是去算出来的hash对n的余数。

put方法就是根据key的哈希值,算出存放的位置,然后取到对应的链表,最后将键值对放入链表。

当然他还会判断是否超出容量,选择resize,根据链表的长度,将链表转化为红黑树,加快hash碰撞太多导致的HashMap的性能降低。

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

get方法也是先算出hash值找到链表,然后再链表里面找到具体的Node,然后返回。

HashMap的ReHash

注意,每次扩容均是将table的长度乘以2

final Node<K,V>[] resize() {
    //省略一些修改容量的代码
  	...
    
    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;
}

当扩容两倍的时候,原来链表的数据在新的结构里分属两个链表,比如长度为16时余数3对应的链表,再扩容为32的时候,那个链表的数据会分别属于余数3对应的链表以及余数19对应的链表,如此就很容易看懂链表的分离了。

LinkedHashMap的有序的实现方式

我们将数据添加到HashMap后,对其遍历的时候是不保证顺序的,如果要保证顺序,就要使用LinkedHashMap,那么他是如何实现有序的呢?

首先我们看HashMap的遍历方式,这是其遍历的核心类:

abstract class HashIterator {
    Node<K,V> next;        // next entry to return
    Node<K,V> current;     // current entry
    int expectedModCount;  // for fast-fail
    int index;             // current slot

    HashIterator() {
        expectedModCount = modCount;
        Node<K,V>[] t = table;
        current = next = null;
        index = 0;
        if (t != null && size > 0) { // advance to first entry
            do {} while (index < t.length && (next = t[index++]) == null);
        }
    }

    public final boolean hasNext() {
        return next != null;
    }

    final Node<K,V> nextNode() {
        Node<K,V>[] t;
        Node<K,V> e = next;
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        if (e == null)
            throw new NoSuchElementException();
        if ((next = (current = e).next) == null && (t = table) != null) {
            do {} while (index < t.length && (next = t[index++]) == null);
        }
        return e;
    }

    public final void remove() {
        Node<K,V> p = current;
        if (p == null)
            throw new IllegalStateException();
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        current = null;
        removeNode(p.hash, p.key, null, false, false);
        expectedModCount = modCount;
    }
}

当我们对HashMap遍历的时候实际上就是调用nextNode(),核心代码是该行:

		if ((next = (current = e).next) == null && (t = table) != null) {
            do {} while (index < t.length && (next = t[index++]) == null);
        }

他实现的是先沿着链表往后遍历,如果找到的为空,那么就沿着table的下表往后遍历,找下一个非空链表返回。

所以HashMap实质是按照hash值来遍历的。

而对于LinkedHashMap,他先对Node对象进行继承,添加了两个属性:

static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
        super(hash, key, value, next);
    }
}

这就使LinkedHashMap的Entry成了三向链表。。。

abstract class LinkedHashIterator {
    LinkedHashMap.Entry<K,V> next;
    LinkedHashMap.Entry<K,V> current;
    int expectedModCount;

    LinkedHashIterator() {
        next = head;
        expectedModCount = modCount;
        current = null;
    }

    public final boolean hasNext() {
        return next != null;
    }

    final LinkedHashMap.Entry<K,V> nextNode() {
        LinkedHashMap.Entry<K,V> e = next;
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        if (e == null)
            throw new NoSuchElementException();
        current = e;
        next = e.after;
        return e;
    }

    public final void remove() {
        Node<K,V> p = current;
        if (p == null)
            throw new IllegalStateException();
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        current = null;
        removeNode(p.hash, p.key, null, false, false);
        expectedModCount = modCount;
    }
}

可以看到他是使用after和before两个属性来完成的遍历,这里我们能够猜到LinkedHashMap使用after和before两个属性,将所有添加的键值对组成了一个双向链表,自然就是有序的了。

那么他如何在添加的时候将其组成链表的呢?

我们发现他并没有重写put方法,其实他是通过如下方法的重写来实现的:

Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
    LinkedHashMap.Entry<K,V> p =
        new LinkedHashMap.Entry<>(hash, key, value, e);
    linkNodeLast(p);
    return p;
}

这是HashMap创建节点的方法,LinkedHashMap重写后,实现了将当前加入的Node添加到上一个Node的后面。

所以LinkedHashMap做到了按添加顺序来遍历(他也可以设置accessOrder属性,达到根据读取的key,来将读取的键值对的位置放到双链表的最后,也就是遍历顺序最后)。

发布了19 篇原创文章 · 获赞 8 · 访问量 4041

猜你喜欢

转载自blog.csdn.net/u014068277/article/details/103759450