1.HashMap
HashMap 实现了基于哈希表的 Map 接口。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。同时还继承了AbstractMap,实现了Cloneable,Serializable 接口。
HashMap是非线程安全的,底层使用的数据结构是数组和链表。当链表长度>=TREEIFY_THRESHOLD -1时,链表会自动变成一棵红黑树。
put方法源码:其中Node存储的是链表节点,TreeNode存储的事红黑树节点;
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;
}
2.HashSet
HashSet是基于HashMap实现的,HashMap的key用来存储数据从而保证数据不会重复,value则是使用的PRESENT对象,该对象为static final。
add方法源码:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
3.HashTable
HashTable与HashMap一样,实现了基于哈希表的 Map 接口,Cloneable及 java.io.Serializable接口。与HashMap不同的是,HashTable是继承自Dictionary类。
put方法源码:
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
由上述源码可知:HashTable是线程安全的,同时key和value的值是不允许为null的。
4.TreeMap
TreeMap继承AbstractMap,实现NavigableMap、Cloneable、Serializable三个接口。其中,NavigableMap是扩展的 SortedMap,具有了针对给定搜索目标返回最接近匹配项的导航方法。
TreeMap底层实现的是红黑树算法。红黑树是每个节点都带有颜色属性的二叉查找树,颜色或红色或黑色。在二叉查找树强制一般要求以外,还有以下几个特性:
性质1. 节点是红色或黑色。
性质2. 根节点是黑色。
性质3 每个叶节点(NIL节点,空节点)是黑色的。
性质4 每个红色节点的两个子节点都是黑色。(从每个叶子到根的所有路径上不能有两个连续的红色节点)
性质5. 从任一节点到其每个叶子的所有路径都包含相同数目的黑色节点。
在TreeMap中存在一个这个的构造方法:
TreeMap(Comparator<? super K> comparator)
其功能是构造一个空的TreeMap,它根据 指定比较器 进行排序。这里的指定比较器就是我们根据需要自己写的“算法”,该构造方法也是设计模式之策略模式(封装了一系列算法,使得它们可以相互替换 )的一个应用。
5.TreeSet
同HashSet是基于HashMap实现一样,TreeSet是基于TreeMap实现的。TreeSet继承自AbstractSet,实现了NavigableSet、Cloneable、Serializable接口。