目录
基本概念
红黑树实现
实现 NavigableMap 接口 具有排序功能
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
基本属性
/**
* 比较器,如果没指定比较器则key要实现Comparable接口重写compareTo方法
* TreeMap有两种方式定义key的比较规则:1:key实现Comparable接口重写compareTo方法;2:通过构造
* 方法 指定构造器
*/
private final Comparator<? super K> comparator;
// 根节点,所有元素都存储在以root为根节点的红黑树中
private transient Entry<K,V> root;
// 实际元素的个数
private transient int size = 0;
// 修改次数,用于快速失败校验
private transient int modCount = 0;
/**
* 存在TreeMap中的元素其实都可以看做是一个Entry对象元素
*/
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left;
Entry<K,V> right;
Entry<K,V> parent;
boolean color = BLACK;
Entry(K key, V value, Entry<K,V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
}
public int hashCode() {
int keyHash = (key==null ? 0 : key.hashCode());
int valueHash = (value==null ? 0 : value.hashCode());
return keyHash ^ valueHash;
}
public String toString() {
return key + "=" + value;
}
}
构造函数
无参构造
/**
* 无参构造方法,key必须实现Comparable接口重写compareTo方法
*/
public TreeMap() {
comparator = null;
}
有参比较器
/**
* 有参构造方法,使用指定的比较器来对key进行比较
*/
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
有参map
/**
* 将传入的Map集合中的元素添加到TreeMap中,key必须实现Comparable接口重写compareTo方法
*/
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
有参有序map
/**
* 将传入的Map集合中的元素添加到TreeMap中,使用传入的Map集合中使用的比较器
*/
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) {
}
}
常用方法
put
/**
* 添加单个元素
*/
public V put(K key, V value) {
Entry<K,V> t = root;
// root根节点为null,这是第一次执行put()操作的时候
if (t == null) {
compare(key, key);
// 第一次执行put()时,将该节点设置为root根节点
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
Comparator<? super K> cpr = comparator;
// 使用指定的比较器来比较大小,当root红黑树中存在此元素时直接替换
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
// 小于0从当前节点的左子树寻找
if (cmp < 0)
t = t.left;
// 大于0从当前节点的右子树寻找
else if (cmp > 0)
t = t.right;
// 等于0,直接更换其value值并返回旧值
else
return t.setValue(value);
} while (t != null);
}
// 根据key中重写的compareTo方法所比较的大小,当root红黑树中存在此元素时直接替换
else {
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
// 小于0从当前节点的左子树寻找
if (cmp < 0)
t = t.left;
// 大于0从当前节点的右子树寻找
else if (cmp > 0)
t = t.right;
// 等于0,直接更换其value值并返回旧值
else
return t.setValue(value);
} while (t != null);
}
// 当root红黑树中不存在此元素时
// 创建Entry对象
Entry<K,V> e = new Entry<>(key, value, parent);
// 此时cmp为比较之后的最后一个节点,小于0将新加的Entry元素添加到左子树
if (cmp < 0)
parent.left = e;
// 大于0将新加的Entry元素添加到右子树
else
parent.right = e;
// 待添加好元素后,平衡红黑树
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
/**
* 比较k1和k2
*/
final int compare(Object k1, Object k2) {
return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
: comparator.compare((K)k1, (K)k2);
}
/**
* 平衡红黑树
*/
private void fixAfterInsertion(Entry<K,V> x) {
x.color = RED;
while (x != null && x != root && x.parent.color == RED) {
if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
Entry<K,V> y = rightOf(parentOf(parentOf(x)));
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
} else {
if (x == rightOf(parentOf(x))) {
x = parentOf(x);
rotateLeft(x);
}
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateRight(parentOf(parentOf(x)));
}
} else {
Entry<K,V> y = leftOf(parentOf(parentOf(x)));
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
} else {
if (x == leftOf(parentOf(x))) {
x = parentOf(x);
rotateRight(x);
}
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateLeft(parentOf(parentOf(x)));
}
}
}
root.color = BLACK;
}
putAll
/**
* 批量添加元素
*/
public void putAll(Map<? extends K, ? extends V> map) {
int mapSize = map.size();
// 当该TreeMap对象中size为0,并且传入的SortedMap对象不为空时
if (size==0 && mapSize!=0 && map instanceof SortedMap) {
Comparator<?> c = ((SortedMap<?,?>)map).comparator();
// comparator和SortedMap对象的比较器一致
if (c == comparator || (c != null && c.equals(comparator))) {
++modCount;
try {
buildFromSorted(mapSize, map.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
return;
}
}
// 调用父类AbstractMap中的putAll()方法
super.putAll(map);
}
/**
* 根据传入的SortedMap构建TreeMap对象
*/
private void buildFromSorted(int size, Iterator<?> it, java.io.ObjectInputStream str, V defaultVal) throws java.io.IOException, ClassNotFoundException {
this.size = size;
// 根据传入的SortedMap构建TreeMap对象实现
root = buildFromSorted(0, 0, size-1, computeRedLevel(size), it, str, defaultVal);
}
/**
* 计算红黑树的高度
*/
private static int computeRedLevel(int sz) {
int level = 0;
for (int m = sz - 1; m >= 0; m = m / 2 - 1)
level++;
return level;
}
/**
* 根据传入的SortedMap构建TreeMap对象实现
*
* @param level 树的高度,初始值为0
* @param lo 子树的第一个元素的索引,初始值为0
* @param hi 子树的最后一个元素的索引,初始值为size-1.
* @param redLevel 哪些节点应该是红色的节点. 它必须和computeRedLevel方法计算出来的一样
*/
private final Entry<K,V> buildFromSorted(int level, int lo, int hi, int redLevel, Iterator<?> it, java.io.ObjectInputStream str, V defaultVal) throws java.io.IOException, ClassNotFoundException {
if (hi < lo) return null;
int mid = (lo + hi) >>> 1;
Entry<K,V> left = null;
if (lo < mid)
left = buildFromSorted(level+1, lo, mid - 1, redLevel,
it, str, defaultVal);
K key;
V value;
if (it != null) {
if (defaultVal==null) {
Map.Entry<?,?> entry = (Map.Entry<?,?>)it.next();
key = (K)entry.getKey();
value = (V)entry.getValue();
} else {
key = (K)it.next();
value = defaultVal;
}
} else { // use stream
key = (K) str.readObject();
value = (defaultVal != null ? defaultVal : (V) str.readObject());
}
Entry<K,V> middle = new Entry<>(key, value, null);
// color nodes in non-full bottommost level red
if (level == redLevel)
middle.color = RED;
if (left != null) {
middle.left = left;
left.parent = middle;
}
if (mid < hi) {
Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
it, str, defaultVal);
middle.right = right;
right.parent = middle;
}
return middle;
}
/**
* 在父类AbstractMap中的putAll()方法中,循环调用put(K key, V value)方法添加元素
*/
public void putAll(Map<? extends K, ? extends V> m) {
// for循环调用put(key,value)方法来添加元素
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}
get
/**
* 根据key来获取value元素
*/
public V get(Object key) {
// 根据key来获取Entry元素
Entry<K,V> p = getEntry(key);
return (p==null ? null : p.value);
}
/**
* 根据key来获取Entry元素
*/
final Entry<K,V> getEntry(Object key) {
if (comparator != null)
return getEntryUsingComparator(key);
// 下面的代码为根据key实现Comparable接口重写compareTo方法来比较key元素的方式
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
Entry<K,V> p = root;
while (p != null) {
// 这里cmp为传入的key与节点元素中的key根据key中重写的compareTo方法所比较的大小
int cmp = k.compareTo(p.key);
// 根据cmp的大小来判断遍历左子树还是右子树
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
/**
* 使用指定的Comparator比较器来比较key
*/
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) {
// 这里cmp为指定的比较器来比较传入的key和节点元素中key元素的大小
int cmp = cpr.compare(k, p.key);
// 根据cmp的大小来判断遍历左子树还是右子树
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
}
return null;
}
总结
红黑树实现
线程不安全
有序