说一下双列集合,顶级接口是Map,实现类有HashMap、LinkedHashMap、TreeMap、HashTable等,使用键值对的格式存储数据,键不可以重复,值可以重复。接下来对实现类做一下详细介绍。
HashMap是最常用的Map集合,它所依赖的数据结构是散列表还有红黑树,添加元素时,现根据添加键值对的key去得到对应的hash值,然后根据hash值和数组的长度确定key在数组中对应的下标位置,然后根据散列是否冲突的原理进行数据添加或者替换(具体分析如下),添加的元素不会进行排序,并且是无序集合。当获取元素时也是根据key键所对应的hash值进行查找的,依赖于数组进行查找,可以达到O(1)的效果,HashMap可以被克隆和序列化,是线程不安全的集合。具体分析如下:
//HashMap对象可被克隆、被序列化
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
//-------------------------------------- 变量 -------------------------------------//
//哈希表
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
//map中键值对的个数,集合的容量
transient int size;
//修改次数
transient int modCount;
//阈值。要调整大小的下一个大小值(容量*负载系数)
int threshold;
//哈希表的负载因子
final float loadFactor;
//默认的初始容量,必须是2的n次幂
//计算结点插入位置时才会取决于hash值,并且保证hash值小于数组长度
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认的加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//使用树而不是列表的计数阈值,当向至少有这么多节点的容器中添加元素时,容器被转换为树。其实一般用到的不多
static final int TREEIFY_THRESHOLD = 8;
//调整大小的计数阈值。操作次数应小于UNTREEIFY_THRESHOLD
static final int UNTREEIFY_THRESHOLD = 6;
//将链表树状化的最小哈希表容量,就是哈希表中达到一定数据时才有必要将链表转化成树
static final int MIN_TREEIFY_CAPACITY = 64;
//基本hash bin结点(就是哈希表中链表中的结点)
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;//记录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;
}
}
//-------------------------------------- 静态的公用方法------------------//
//重要函数,计算hash值
static final int hash(Object key) {
int h;
//key.hashCode():返回key的哈希码值与哈希值的高16位进行异或运算
//使得位置尽量分散
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//只有传入的对象的运行时类型实现了Comparable才会被返回,否则返回null
static Class<?> comparableClassFor(Object x) {
//判断当前对象是否实现了比较器接口
if (x instanceof Comparable) {
Class<?> c;
Type[] ts, as;
Type t;
ParameterizedType p;
if ((c = x.getClass()) == String.class)
return c;
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (
((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() == Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1
&& as[0] == c
)
return c;
}
}
}
return null;
}
//只有传入的对象x和kc的类型相同时才进行比较
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
static int compareComparables(Class<?> kc, Object k, Object x) {
return (x == null || x.getClass() != kc ? 0 :
((Comparable)k).compareTo(x));
}
//返回一个最接近2的幂并且大于cap的整数
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
//-------------------------------------- 构造方法-------------------//
//根据初始大小和负载因子创建实例
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
//将最接近2的幂并且大于initialCapacity的整数作为阈值
this.threshold = tableSizeFor(initialCapacity);
}
//根据初始大小和负载因子创建实例
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
//-------------------------------------- 功能方法-------------------//
//集合中键值对个数
public int size() {
return size;
}
//-------------------------------------- 获取方法 ------------------//
//根据键获取值
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;
//如果当前哈希表不为空 && 哈希表中的键值对个数大于0 && key所对应位置上的值不为null则继续进行
//(n - 1) & hash:用来获取key的hash值对应数组的下标
//n = tab.length n-1则一定小于数组的长度,并且数组的长度为2的n次幂
//与hash值做与运算则可以保证key值对应的hash值和数组的下标有关系并且不大于数组的长度,当n=16时,如下:
//00000000 00010000 十进制减去1,则得到 00000000 00001111 ,所以与hash做与运算,则得到的下标值是根据哈希值得到的并且一定小于16
//00000000 00001111
//00000010 10110101 &
//-------------------------
//00000000 00000101
//这也是为什么数组的大小一定要是2的n次幂的原因
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null)
{
//如果结点first的hash值和key值均相等则可确定key对应的结点就是first,直接返回
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
{
return first;
}
//key不相等,如果first结点存在后继结点,则继续程序
if ((e = first.next) != null) {
//如果first是树结点,则按着树的规则获取值
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//如果first不是树结点,则遍历链表的每一个结点,key相同时,返回对应值
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
//-------------------------------------- 添加方法 ------------------//
//添加键值对(修改键对应的值)
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;
}
//根据hash值获取指定位置上的value,如果value==null,说明没有hash冲突,则直接添加此结点
if ((p = tab[i = (n - 1) & hash]) == null){
tab[i] = newNode(hash, key, value, null);
}else {//存在hash冲突
Node<K,V> e; K k;
//key相同,则覆盖之前的key所对应的value
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 {//存在冲突,使用链表的方式解决冲突,则遍历链表,如果存在相同的key,则覆盖vlaue,不存在则添加到末端
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//判断是否需要将链表转成红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) {
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;
}
//初始化哈希表或者对哈希表进行扩容
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//如果旧的数组长度大于0
if (oldCap > 0) {
//如果数组长度已经达到最大值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//如果旧的数组长度未达到最大值,则将旧的数组的长度扩展一倍作为新数组的长度
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;
} else if (oldThr > 0){
newCap = oldThr;
} else {//数组为空,初始化数组长度和阈值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//如果新的散列的阈值等于0
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) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[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 { //存在冲突,使用链表结构存储
//重新散列,并不是将链表复制过去
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 {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
//将链表转换成红黑树
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();
} else 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;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null){
hd.treeify(tab);
}
}
}
//-------------------------------------- 删除方法 -----------------//
//根据key删除键值对
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;
//如果key的hash码所对应数组下标位置上存在值,则继续程序
if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//如果hash值相同,并且key相同,则说明没有冲突,获取结点
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))){
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);
}
}
//如果结点不为空,则说明存在key对应的结点,则删除
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;
}
//-------------------------------------- 遍历操作 --------------------//
//获取哈希表中所有键值对的key
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
//获取hash表中所有的value
public Collection<V> values() {
Collection<V> vs = values;
if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
}
final class Values extends AbstractCollection<V> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<V> iterator() { return new ValueIterator(); }
public final boolean contains(Object o) { return containsValue(o); }
public final Spliterator<V> spliterator() {
return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
//将hash表中所有的键值键值对放到一个set集合中
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
public final boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Node<K,V> candidate = getNode(hash(key), key);
return candidate != null && candidate.equals(e);
}
public final boolean remove(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Object value = e.getValue();
return removeNode(hash(key), key, value, true, true) != null;
}
return false;
}
public final Spliterator<Map.Entry<K,V>> spliterator() {
return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
//-------------------------------------- 克隆操作 -------------------//
@SuppressWarnings("unchecked")
@Override
public Object clone() {
HashMap<K,V> result;
try {
result = (HashMap<K,V>)super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
result.reinitialize();
result.putMapEntries(this, false);
return result;
}
//-------------------------------------- 序列化操作 -----------------//
//序列化
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
//删除具体代码
}
//反序列化
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException {
//删除具体代码
}
//hashmap中维护一个红黑树结点静态内部类,里边有着一系列处理红黑树的方法
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent;
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev;
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
}
}
再说一下Hashtable,它的实现和HashMap基本相同,但是在功能上也存在几点不同,分析如下:
//继承了Dictionary
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, java.io.Serializable {
//
private transient Entry<?,?>[] table;
//键值对个数
private transient int count;
//阈值
private int threshold;
//加载因子
private float loadFactor;
//修改次数
private transient int modCount = 0;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//-------------------------------构造方法 ------------------------------//
public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load: "+loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
table = new Entry<?,?>[initialCapacity];
threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}
public Hashtable(int initialCapacity) {
this(initialCapacity, 0.75f);
}
public Hashtable() {
this(11, 0.75f);
}
//-------------------------------功能方法 ------------------------------//
//返回Enumeration集合,HashMap中是没有的
public synchronized Enumeration<K> keys() {
return this.<K>getEnumeration(KEYS);
}
//HashMap中没有这个方法
public synchronized boolean contains(Object value) {
if (value == null) {
throw new NullPointerException();
}
Entry<?,?> tab[] = table;
for (int i = tab.length ; i-- > 0 ;) {
for (Entry<?,?> e = tab[i] ; e != null ; e = e.next) {
if (e.value.equals(value)) {
return true;
}
}
}
return false;
}
//-------------------------------获取方法 ------------------------------//
//synchronized修饰,方法实线程同步的
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
//获取下标的方式不同,直接使用hash值进行下标获取
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
//-------------------------------添加方法 ------------------------------//
public synchronized V put(K key, V value) {
//value不可以为空,HashMap中就可以
if (value == null) {
throw new NullPointerException();
}
//判断是否已经存在此key对应的键值对
//如果存在则替换
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;
}
//具体添加方法
private void addEntry(int hash, K key, V value, int index) {
modCount++;
Entry<?,?> tab[] = table;
if (count >= threshold) {//如果哈希表中的键值对数量大于阈值,则扩容
rehash();
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
//添加
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
//扩容操作
@SuppressWarnings("unchecked")
protected void rehash() {
int oldCapacity = table.length;
Entry<?,?>[] oldMap = table;
// 扩容成一倍+1,HashMap是一倍
int newCapacity = (oldCapacity << 1) + 1;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (oldCapacity == MAX_ARRAY_SIZE)
return;
newCapacity = MAX_ARRAY_SIZE;
}
Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
modCount++;
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = (Entry<K,V>)newMap[index];
newMap[index] = e;
}
}
}
//Hashtable中不会牵扯到红黑树的操作
}
说一下TreeMap,它依赖于红黑树实现,添加的元素是可以按着关键字排序的,排序规则可以自定义,分析如下:
public interface SortedMap<K,V> extends Map<K,V> {}
public interface NavigableMap<K,V> extends SortedMap<K,V> {}
//基于红黑树的实现
//红黑树:是一种大致平衡的平衡二叉树,根节点和叶子节点是黑色,其他节点是黑色或者红色,
//每个红色节点的两个子节点是黑色,从每个叶子到根的所有路径上不能有两个连续的红色节点
//从任意一节点到其每个叶子节点的所有路径都包含相同数目的黑色节点
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
//比较器,用于维护树中元素的顺序
private final Comparator<? super K> comparator;
//树
private transient Entry<K,V> root;
//节点个数
private transient int size = 0;
//修改次数
private transient int modCount = 0;
//------------------------------构造函数--------------------//
public TreeMap() {
comparator = null;
}
//自定义构造器初始化TreeMap
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
//根据现有的TreeMap构建一个TreeMap实例
public TreeMap(SortedMap<K, ? extends V> m) {
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
//树中所含元素个数
public int size() {
return size;
}
//------------------------------ 添加元素 --------------------//
//添加元素
public V put(K key, V value) {
Entry<K,V> t = root;
//初始化根节点
if (t == null) {
compare(key, key);
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
//如果已经有数据了
int cmp;
Entry<K,V> parent;
//获取到比较器
Comparator<? super K> cpr = comparator;
if (cpr != null) {//如果比较器不为空,按着比较器规则比较
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)//如果cmp<0,继续比较左子树
t = t.left;
else if (cmp > 0)//如果cmp>0,继续比较右子树
t = t.right;
else
return t.setValue(value);//值相同,直接覆盖
} while (t != null);
} else {//没有比较器,默认比较器比较
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
//添加节点
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
//------------------------------ 获取元素 --------------------//
//根据key获取value
public V get(Object key) {
Entry<K,V> p = getEntry(key);
return (p==null ? null : p.value);
}
//获取值的具体操作
final Entry<K,V> getEntry(Object key) {
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
//根据默认的比较器查找对应key的value值
Comparable<? super K> k = (Comparable<? super K>) key;
Entry<K,V> p = root;
while (p != null) {
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
//根据自定义比较器查找key对应的value值
final Entry<K,V> getEntryUsingComparator(Object key) {
K k = (K) key;
Comparator<? super K> cpr = comparator;
if (cpr != null) {
Entry<K,V> p = root;
while (p != null) {
int cmp = cpr.compare(k, p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
}
return null;
}
//------------------------------ 移除元素 --------------------//
//根据key获取到节点,然后返回对应值,删除节点
public V remove(Object key) {
Entry<K,V> p = getEntry(key);
if (p == null)
return null;
V oldValue = p.value;
deleteEntry(p);
return oldValue;
}
//删除的具体操作
private void deleteEntry(Entry<K,V> p) {
modCount++;
size--;
//如果被删除的节点有左右子结点
if (p.left != null && p.right != null) {
Entry<K,V> s = successor(p);
p.key = s.key;
p.value = s.value;
p = s;
}
Entry<K,V> replacement = (p.left != null ? p.left : p.right);
if (replacement != null) {
replacement.parent = p.parent;
if (p.parent == null)
root = replacement;
else if (p == p.parent.left)
p.parent.left = replacement;
else
p.parent.right = replacement;
p.left = p.right = p.parent = null;
if (p.color == BLACK)
fixAfterDeletion(replacement);
} else if (p.parent == null) { //删除唯一的节点
root = null;
} else { // 删除的节点没有子节点,直接删除即可
if (p.color == BLACK)
fixAfterDeletion(p);
if (p.parent != null) {
if (p == p.parent.left)
p.parent.left = null;
else if (p == p.parent.right)
p.parent.right = null;
p.parent = null;
}
}
}
//删除一个节点,依次移动节点,以保证平衡
static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
if (t == null)
return null;
else if (t.right != null) {
Entry<K,V> p = t.right;
while (p.left != null)
p = p.left;
return p;
} else {
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
while (p != null && ch == p.right) {
ch = p;
p = p.parent;
}
return p;
}
}
//还有一些其他的不同于HahhMap的方法,在这里不做介绍
}
最后说一下LinkedHashMap,它继承自HashMap,它将集合中的元素使用一个双向链表进行连接,在存取上是有序的,LinkedHashMap可以看成是使用HashMap进行存储元素+链表链接元素保证顺序,分析如下:
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
{
//每一个结点添加before、after属性,用来记录存取顺序
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
//双向链表的头结点
transient LinkedHashMap.Entry<K,V> head;
//双向链表的尾节点
transient LinkedHashMap.Entry<K,V> tail;
//以什么顺序进行链接,
//accessOrder为true时按访问顺序
//accessOrder为false时按插入顺序,默认
final boolean accessOrder;
//---------------------------构造函数----------------------//
//使用父类构造方法
public LinkedHashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
accessOrder = false;//默认按插入顺序
}
public LinkedHashMap(int initialCapacity) {
super(initialCapacity);
accessOrder = false;//
}
public LinkedHashMap() {
super();
accessOrder = false;
}
public LinkedHashMap(Map<? extends K, ? extends V> m) {
super();
accessOrder = false;
putMapEntries(m, false);
}
//---------------------------功能函数----------------------//
//---------------------------添加方法----------------------//
//用的时HashMap中的put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//具体添加,onlyIfAbsent,evict这两个参数发挥作用
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) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);//按访问顺序
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//按访问顺序链接,将结点链接到最后
void afterNodeAccess(Node<K,V> e) {
LinkedHashMap.Entry<K,V> last;
if (accessOrder && (last = tail) != e) {
LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a != null)
a.before = b;
else
last = b;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
tail = p;
++modCount;
}
}
//LinkedHashMap就是用一个双向链表将HashMap中的元素链接起来保证有序,这里只说一个保持顺序的方法
}
以上是对Map集合做一下简单介绍。