1、TreeMap
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;
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;
public int hashCode() {
int keyHash = (key == null ? 0 : key.hashCode());
int valueHash = (value == null ? 0 : value.hashCode());
return keyHash ^ valueHash;
}
}
}
comparator可以在构造时指定,未指定则利用Comparable<? super K> k = (Comparable<? super K>) key,key要实现Comparable接口
有subMap()方法可以返回子树
有floorEntry(≤),lowerEntry(<),ceilingEntry(≥),higherEntry(>)等方法,返回key ≤ | < | ≥ | > 入参的entry
如下,floorEntry()和lowerEntry()的区别在于cmp = 0时的处理
有successor(Entry<K, V> t)返回中序遍历的下一个节点:t有右儿子就找到右儿子最左的节点,无右儿子就上溯父节点,直到t所在子树是父节点的左子树,返回该父节点
2、TreeSet
用private transient NavigableMap<E,Object> m实现,如果构造时不传入NavigableMap默认用TreeMap