HashMap, HashTable, TreeMap

194 阅读4分钟

前言

前面讲完了集合框架家族 ListQueue 的实现类
Set 实现类之前,我想先来聊下 Map 底下三大实现类
注意:Map不属于集合框架家族

HashMap

public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

HashMap 构造器和静态对象

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;

DEFAULT_LOAD_FACTOR
当数据量达到最大容量的某个比例, 扩容 table
TREEIFY_THRESHOLD
当单个 bucket 里面的元素大于此值,转换为树结构
UNTREEIFY_THRESHOLD
当单个 bucket 里面的元素大于此值,转回 bucket 结构 MIN_TREEIFY_CAPACITY
当容量大于此值时才能开始转换 bucket 到树结构
table
存储 bucket 的数组

继续看一下bucket的实现方法:

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
}

bucket的实现方式就是一个简单的单向链表

HashMap 哈希值

先来看一下源码中的哈希值计算方法:

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

哈希值的计算步骤:

  1. 调用Object.hashCode找到key的哈希值
  2. 哈希值的前一半等于key的哈希值前一半
  3. 哈希值的后一半等于 (哈希值前一半XOR哈希值后一半)

再来看一下哈希值的使用方法:

if ((p = tab[i = (n - 1) & hash]) == null)
       tab[i] = newNode(hash, key, value, null);

(n-1)&hash 用数组长度AND哈希值来找到对应bucket
注意:找到对应 bucket 之后,最后存储到Node<K,V>
里面的哈希值是 hash(Object key)的结果

HashMap 增删(bucket)

源码中put调用了putVal来实现插入,来看下:

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的插入有以下步骤:

  1. 如果table为空,调用resize()来初始化数组
  2. 如果bucket为空,在当前桶创建新的链表
  3. 如果bucket不为空,树结构直接调用putTreeVal
  4. 如果bucket不为空且为链表,尾部插入检测Treeify
  5. 调整key对应的value 返回oldValue
  6. 如果没有在链表或树中插入元素,检测bucket扩容需求

再来看一下删除操作

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

跟之前逻辑一样,如果在链表中找到了,执行最基本的链表中删除
单个元素的算法。如果在Tree中找到,调用removeTreeNode

HashMap 查询(bucket)

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

查询函数很简单,找到对应bucket并且遍历链表/红黑树
时间复杂度O(1),链表最差O(n),红黑树最差O(logn)

红黑树

之前提到的增删查询操作主要是针对数组+链表的数据结构
在桶中collision过多的时候,转换链表为红黑树可以提高
索引效率,我们先来看下红黑树的基本概念。

HashMap Treeify

简单的来看一下HashMap中转换红黑树的做法:

final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        TreeNode<K,V> hd = null, tl = null;
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}

数组+链表实现了初始HashMap储存方式
bucket collision 大于8且达到转换要求,转换红黑树 当红黑树中元素小于6,转换回链表

Hashtable

我们只需要看一下源码对Hashtable的建议就可以了:

 * Java Collections Framework</a>.  Unlike the new collection
 * implementations, {@code Hashtable} is synchronized.  If a
 * thread-safe implementation is not needed, it is recommended to use
 * {@link HashMap} in place of {@code Hashtable}.  If a thread-safe
 * highly-concurrent implementation is desired, then it is recommended
 * to use {@link java.util.concurrent.ConcurrentHashMap} in place of
 * {@code Hashtable}.

Hashtable是线程安全的HashMap
如果有高并发需求,应该使用ConcurrentHashMap

TreeMap

TreeMap顾名思义是对key排序的HashMap实现方式
对比HashMapTreeMap直接使用红黑树,有效率损失

TreeMap 在红黑树基础上,使用对比器找到增删位置
线程不安全,优先使用HashMap

关于红黑树和 binary heap 的思考

其实红黑树实现了二叉堆的局部最值的概念。当你只在意全局最值的时候,把<Key,Value>作为单一元素来实现PriorityQueue应该是最方便的办法。如果你需要访问其他元素,那么TreeMap的额外空间使用就是合理的。

下一篇文章

Set 家族实现类:HashSet, LinkedHashSet, TreeSet