• 是一种键值对(K-V)形式的存储结构
  • HashMap是否允许空:Key和Value都允许为空
  • HashMap是否允许重复数据:Key重复会覆盖、Value允许重复
  • HashMap是否有序:无序,特别说明这个无序指的是遍历HashMap的时候,得到的元素的顺序基本不可能是put的顺序
  • HashMap是否线程安全:非线程安全
  • HashMap的一个存储单元
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
        .....
}
  • 在 JDK1.8 中,HashMap 是由 位桶+链表/红黑树构成,新增了红黑树作为底层数据结构,当某个位桶的链表的长度达到某个阀值的时候,这个链表就将转换成红黑树。当同一个hash值的节点数不小于8时,将不再以单链表的形式存储了,会被调整成一颗红黑树。这就是JDK7与JDK8中HashMap实现的最大区别
/**
     * 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;
  • 主要字段
    transient Node<K,V>[] table;//初始化使用,长度总是 2的幂
    transient Set<Map.Entry<K,V>> entrySet;//保存缓存的entrySet()
    transient int size;//此映射中包含的键值映射的数量(集合存储键值对的数量)
    transient int modCount;//跟前面ArrayList和LinkedList集合中的字段modCount一样,记录集合被修改的次数,主要用于迭代器中的快速失败
    int threshold;//调整大小的下一个大小值(容量*加载因子)capacity * load factor
    final float loadFactor;//散列表的加载因子
  • hash算法
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//取 hashCode 值: key.hashCode();高位参与运算:h>>>16
    }
  • 添加方法
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)//通过 hash & (table.length -1)来得到该对象的保存位
            tab[i] = newNode(hash, key, value, null);//tab[i] 为null,直接将新的key-value插入到计算的索引i位置
        else {//tab[i] 不为null,表示该位置已经有值了
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;//节点key已经有值了,直接用新值覆盖
            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) //链表长度大于8,转换成红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))//key已经存在直接覆盖value
                        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;
    }
  • 扩容机制
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) {//数组大小如果已经大于等于最大值(2^30)
                threshold = Integer.MAX_VALUE;//修改阈值为int的最大值(2^31-1),这样以后就不会扩容了
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)//原数组长度大于等于初始化长度16,并且原数组长度扩大1倍也小于2^30次方
                newThr = oldThr << 1; // 阀值扩大1倍
        }
        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) {//把每个bucket都移动到新的buckets中
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;//元数据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 {//原索引+oldCap
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {//原索引放到bucket里
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {//原索引+oldCap放到bucket里
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

该方法分为两部分,首先是计算新桶数组的容量 newCap 和新阀值 newThr,然后将原集合的元素重新映射到新集合中。

  • 删除方法
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) {//(n - 1) & hash找到桶的位置
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))//如果键的值与链表第一个节点相等,则将 node 指向该节点
                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;
    }
  • 查找方法
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 && //根据key计算的索引检查第一个索引
                ((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<String, String> map = new HashMap<>();
map.put("1", "A");
map.put("2", "B");
map.put("3", "C");
map.put("4", "D");
map.put("5", "E");
map.put("6", "F");
for(String str : map.keySet()){
    System.out.print(map.get(str)+" ");
}

for(HashMap.Entry entry : map.entrySet()){
    System.out.print(entry.getKey()+" "+entry.getValue());
}
  • HashMap和Hashtable的区别

Hashtable是线程安全的,Hashtable所有对外提供的方法都使用了synchronized,也就是同步,而HashMap则是线程非安全的

Hashtable不允许空的value,空的value将导致空指针异常,而HashMap则无所谓,没有这方面的限制

两个的rehash算法不同

 

Leave a comment

电子邮件地址不会被公开。 必填项已用*标注