常⽤数据结构——Map
环境:JDK1.8
HashMap
1、底层为数组+链表(当容量达到8时变为红⿊树)
2、⾮线程安全;
3、key和value均可为null;
4、初始容量为16;
5、最⼤容量为MAXIMUM_CAPACITY = 1 << 30=2^30
6、负载因⼦为0.75,意思是⽐如我初始容量为16,那么当键值对超过16*0.75=12时就会进⾏扩容,新容量=旧容量*2;
7、扩容条件:1 元素数量达到阈值;2 HashMap准备树形化时发现数组长度太短(长度⼩于MIN_TREEIFY_CAPACITY=64)
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which ca resizes instead.
*/
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();
el 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;
el {
p.prev = tl;
< = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
}
}
8、初始容量尽量设置为2的幂次,便于底层进⾏位移运算,;
9、HashMap容量=initailCapacity*loadFactor;
10、put⽅法:先根据key的hash值得到这个元素在数组中的位置(即下标),然后就可以把这个元素放到对应的位置中了。如果这个元素所在的位⼦上已经存放有其他元素了,那么在同⼀个位⼦上的元素将以链表的形式存放,新加⼊的放在链头,最先加⼊的放在链尾。
11、get⽅法:⾸先计算key的hashcode,找到数组中对应位置的某⼀元素,然后通过key的equals⽅法在对应位置的链表中找到正确的节点,即能找到需要的元素。
12、获取value:Object (key);
13、获取key:
/
/ key的集合
Set t=map.keySet() ;
// key value的集合
Set<Map.Entry<String, Object>> entries = Set();
遍历⽅式
Iterator<Map.Entry<String, Integer>> entryIterator = Set().iterator();
while (entryIterator.hasNext()) {
Map.Entry<String, Integer> next = ();
System.out.println("key=" + Key() + " value=" + Value());
}
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()){
String key = ();
System.out.println("key=" + key + " value=" + (key));
}
map.forEach((key,value)->{
System.out.println("key=" + key + " value=" + value);
});
建议使⽤第⼀种EntrySet遍历⽅式
第⼀种可以把key和value同时取出来;
第⼆种要先取出key,再去取value,效率较低;
第三种是JDK1.8及以上,通过外层遍历table,内层遍历链表或红⿊树
ConcurrentHashMap
1、ConcurrentHashMap采⽤了分段锁技术,其中Segment继承于 ReentrantLock;
源码如下:
/**
* Stripped-down version of helper class ud in previous version,
* declared for the sake of rialization compatibility
*/
static class Segment<K,V> extends ReentrantLock implements Serializable {
private static final long rialVersionUID = 2249069246763182397L;
final float loadFactor;
Segment(float lf) { this.loadFactor = lf; }
}
2、get⽅法,ConcurrentHashMap 的 get ⽅法是⾮常⾼效的,因为整个过程都不需要加锁。
只需要将 Key 通过 Hash 之后定位到具体的 Segment ,再通过⼀次 Hash 定位到具体的元素上。由于 Node中的 value 属性是⽤volatile 关键词修饰的,保证了内存可见性,所以每次获取时都是最新值
/**
* 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.equals(k)},
* then this method returns {@code v}; otherwi it returns
* {@code null}. (There can be at most one such mapping.)
*
* @throws NullPointerException if the specified key is null
*/
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
el if (eh < 0)
return (p = e.find(h, key)) != null ? p.val : null;
while ((e = e.next) != null) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}
3、put⽅法:
虽然 Node中的 value 是⽤ volatile 关键词修饰的,但是并不能保证并发的原⼦性,所以 put 操作时仍然需要加锁处理。
⾸先也是通过 Key 的 Hash 定位到具体的 Segment,在 put 之前会进⾏⼀次扩容校验。这⾥⽐ HashMap 要好的⼀点是:HashMap 是插⼊元素之后再看是否需要扩容,有可能扩容之后后续就没有插⼊就浪费了本次扩容(扩容⾮常消耗性能)。
⽽ ConcurrentHashMap 不⼀样,它是先将数据插⼊之后再检查是否需要扩容,之后再做插⼊。
/**
* Key-value entry. This class is never exported out as a
* ur-mutable Map.Entry (i.e., one supporting tValue; e
* MapEntry below), but can be ud for read-only traversals ud
* in bulk tasks. Subclass of Node with a negative hash field
* are special, and contain null keys and values (but are never
* exported). Otherwi, keys and vals are never null.
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;
volatile Node<K,V> next;
Node(int hash, K key, V val, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.val = val;
< = next;
}
public V put(K key, V value) {
return putVal(key, value, fal);
}
/** Implementation for put and putIfAbnt */
/
** Implementation for put and putIfAbnt */
final V putVal(K key, V value, boolean onlyIfAbnt) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
el if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin }
el if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
el {
V oldVal = null;
synchronized (f) { //此处加锁
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbnt)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
< = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
el if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbnt)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}