Java数据结构的映射定义了一个接口java.util.Map,此接口有四个常用实现类,分别为HashMap、Hashtable、LinkedHashMap、TreeMap
HashMap: 它根据键的hashcode值存储数据,大多数情况下可以直接定位到它的位置,但是遍历顺序不一致,HashMap最多只允许一条记录的键为null,允许多条记录的值为null,HashMap非线程安全,可能出现死循环或者数据不一致,若要达到线程安全,可以使用Collections的sychronizedMap方法具有线程安全能力或者使用ConcurrentHashMap.
Hashtable:hashtable是遗留类,和HahMap的不同点主要有它继承于Dictionary类,并且是线程安全的,任何一个时间只有一个线程可以写Hashtable,并发性不如ConcurrentHashMap,因为ConcurrentHashMap引入了分段锁。
LinkedHashMap:LinkedHashMap 是HashMap的一个子类,保存了记录的插入顺序,在用iterator()遍历LinkedHashMa时,先得到的记录肯定说先插入,
TreeMap:TreeMap实现SoredMap接口,能够把它保存的记录根据键来排序,默认按照键的升序来排序。当用TreeMap遍历TreeMap时,得到的记录时排过序的。
1.HashMap的数据结构
transient Node<K,V>[] table;
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;
}
}
哈希表结构(链表散列:数组+链表)实现,结合数组和链表的优点。当链表长度超过 8 时,链表转换为红黑树。
2.HashMap的工作原理(存储和获取)
2.1 存储
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;
}
- 确定哈希桶数组索引位置
static final int hash(Object key) { int h; // h = key.hashCode() 为第一步 取hashCode值 // h ^ (h >>> 16) 为第二步 高位参与运算 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
调用hash(K)方法计算k的hash值,结合数据长度得到下标,减少系统的开销,也不会造成因为高位没有参与下标的计算,从而引起的碰撞。
-
当容器元素个数大于capacity*loadfactor时,容器扩容为2n
-
在插入时又分以下情况 :1. 如果hash值在HashMap中不存在,则插入,若存在,则发生碰撞. 2.如果k的hash值在HashMap中存在,且二者equals返回为true则更新键值对,3.如果k的hash值在HashMap中存在,且二者equals返回为false则插入链表尾部(尾插法)或者红黑树中(树的添加方式)。
2.2获取
获取对象时将k传给get()方法:1.调用hash(K)方法(计算k的Hash值)从而获取下标,2顺序遍历链表,equals()方法查找相同Node链表中k值对应的V值。