从网上看了许多关于treemap集合的底层,还是有点懵懂,大概意思是这样,首先treemap的底层是一个二叉树(自平衡的红黑树),比如说当我们在treemap中插入元素的时候,内部其实有一个比较器( cmp = cpr.compare(key, t.key);)首先先将新插入的key值与根节点的key值(应该是调用 cmp = cpr.compare(key, t.key)所得的值是否为正数还是负数,)比较,如果比跟姐点的key值大,那么在于二叉树的右子树进行比较,同理如果比根节点的key值小,呢么再与二叉树的左子树进行比较,如果两者的key值相等,就用新插入的key值所对应的的value值将旧的value进行替换。
int cmp;
Entry<K,V> parent;
Comparator<? super K> cpr = comparator;
// 如果比较器 cpr 不为 null,即表明采用定制排序
if (cpr != null)
{
do {
// 使用 parent 上次循环后的 t 所引用的 Entry
parent = t;
// 拿新插入 key 和 t 的 key 进行比较
cmp = cpr.compare(key, t.key); //important!!!!
// 如果新插入的 key 小于 t 的 key,t 等于 t 的左边节点
if (cmp < 0)
t = t.left;
// 如果新插入的 key 大于 t 的 key,t 等于 t 的右边节点
else if (cmp > 0)
t = t.right;
// 如果两个 key 相等,新的 value 覆盖原有的 value,
// 并返回原有的 value
else
return t.setValue(value);
} while (t != null);
}