TreeMap和TreeSet
TreeMap概述
TreeMap是Map的一个实现类,底层使用红黑树,存储元素有序,可自定义比较器;对于存储在TreeMap的元素必须是可比较的。
TreeMap中的红黑树结点,使用静态内部类实现:
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; // 颜色 }
-
TreeMap中的成员变量:
private final Comparator<? super K> comparator; // 比较器
-
当使用无参构造的时候,使用默认的比较器(由传入对象自身的比较器决定);否则,将外部比较器赋值
public TreeMap(Comparator<? super K> comparator) { this.comparator = comparator; }
-
对于添加元素put()的流程,先按照查找的原则根据比较器排列,然后再进行红黑树的调整
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++; // fast-fail中涉及,避免并发修改 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) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } else { // 内部排序器 if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") // 因为可排序的对象都要事先Comparable接口 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; }
红黑树的具体实现没整理。。。
TreeSet
对于Set集合,HashSet和TreeSet底层都是使用对应的HashMap和TreeMap实现的。
private transient NavigableMap<E,Object> m; // TreeMap中实现了这个接口 public TreeSet() { this(new TreeMap<E,Object>()); }
其他的方法更多是调用m对象的方法,具体实现就是根据多态了。
上一篇:
多线程四大经典案例
下一篇:
RabbitMQ的基础学习(上)