概述
TreeMap 是 Java 中基于 红黑树(Red-Black Tree) 实现的有序映射,支持自定义的排序规则。
不得不提,TreeMap 的代码读起来,既精简又优雅,很适合学习红黑树。
一、数据结构与节点定义
1. 节点类(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;
}
}