Map概览
Map提供的是对象和对象的关联。
- HashMap
HashMap是以哈希表来实现的,查找对象时通过哈希函数计算其位置。
- LinkedHashMap
LinkedHashMap继承自HashMap,其定义如下:
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> {
- WeakHashMap
WeakHashMap是一种改进的HashMap。
public class WeakHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V> {
- TreeMap
TreeMap实现了SortedMap接口,其内部是以红黑树来实现的。
- Hashtable
Hashtable是以哈希表来实现的,解决冲突的方式与HashMap一样,也是采用了散列链表的形式,不过性能比HashMap要低。
源码解读
HashMap无参构造函数的定义如下:
/** * Constructs an empty {@code HashMap} with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }
HashMap是一个数组和链表的结合体(在数据结构称“链表散列”),其中数组的定义如下:
/** * The table, initialized on first use, and resized as * necessary. When allocated, length is always a power of two. * (We also tolerate length zero in some operations to allow * bootstrapping mechanics that are currently not needed.) */ transient Node<K,V>[] table;
/** * Basic hash bin node, used for most entries. (See below for * TreeNode subclass, and in LinkedHashMap for its Entry subclass.) */ 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; } }
put()
当往HashMap中添加元素的时候,先根据key的hash值得到这个元素在数组中的位置(即下标),然后把这个元素放到对应的位置中。
如果这个元素所在的位置上已经存放有其他元素,那么在同一个位置上的元素将以链表的形式存放,新加入的元素放在链头,之前的元素放在链尾,如下图所示:
对应源代码如下:
/** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with {@code key}, or * {@code null} if there was no mapping for {@code key}. * (A {@code null} return can also indicate that the map * previously associated {@code null} with {@code key}.) */ public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
/** * Implements Map.put and related methods. * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. * @return previous value, or null if none */ 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; }
get()
方法的示意图如下:
对应源代码如下:
/** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @see #put(Object, Object) */ public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; }
/** * Implements Map.get and related methods. * * @param hash hash for key * @param key the key * @return the node, or null if none */ 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; }
Note
(1)如果使用自定义对象作为Key,需要确保其实现了hashCode()和equals()方法。
(2)HashMap中hash数组的默认大小是16;默认负载因子是0.75。
(3)HashMap根据需要可能会对元素重新哈希,元素的顺序会被打散,因此不同时间迭代同一个HashMap的顺序可能会不同。
(4)针对null元素,HashMap在存储Entry对象时检查键是否为空,如果键为空,则始终将其映射到桶0。
/** * Computes key.hashCode() and spreads (XORs) higher bits of hash * to lower. Because the table uses power-of-two masking, sets of * hashes that vary only in bits above the current mask will * always collide. (Among known examples are sets of Float keys * holding consecutive whole numbers in small tables.) So we * apply a transform that spreads the impact of higher bits * downward. There is a tradeoff between speed, utility, and * quality of bit-spreading. Because many common sets of hashes * are already reasonably distributed (so don't benefit from * spreading), and because we use trees to handle large sets of * collisions in bins, we just XOR some shifted bits in the * cheapest possible way to reduce systematic lossage, as well as * to incorporate impact of the highest bits that would otherwise * never be used in index calculations because of table bounds. */ static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
(5)当get()方法返回null时,既可以表示 HashMap中没有该键,也可以表示该键所对应的值为null,所以不能由get()方法来判断是否存在某个键,而应该用containsKey()方法来判断
(6)java.util.concurrent.ConcurrentHashMap是HashMap的线程安全版
变更
HashMap implementation changes in Java 8
在 Hash 函数将对象均匀分布在桶中的理想情况下,HashMap为 get() 和 put() 方法提供了恒定的时间性能 O(1)。
但是,如果 hashCode() 存在大量冲突,则性能可能会恶化。
在散列冲突的情况下,对象被存储为链表中的一个结点,并且使用 equals() 方法来比较Key。
在链表中找到正确Key的比较是一个线性操作,在最坏的情况下,时间复杂度变为 O(n)。
Java 8 为了解决这个问题,在达到某个阈值后,使用平衡树。
这意味着 HashMap 初始将 Entry 对象存储在链表中,但当链表中的元素数目大于某个阈值后,将链表变为平衡树,这使最坏情况下的性能为 O(log n)。