public interface SortedMap<K,V> extends Map<K,V> {
}
public interface NavigableMap<K,V> extends SortedMap<K,V> {
}
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>{
//外置比较器
private final Comparator<? super K> comparator;
//元素个数
private transient int size = 0;
//操作数
private transient int modCount = 0;
public TreeMap() {
comparator = null;//外置比较器设置为null
}
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;//赋值外置比较器
}
public V put(K key, V value) {
//获取外置比较器
Comparator<? super K> cpr = comparator;
//判断是否有外置比较器
if (cpr != null) {//说明有外置比较器
//使用外置比较器的排序规则
}else {//说明没有外置比较器
//使用内置比较器的排序规则
}
size++;
modCount++;
return null;
}
}
public interface SortedSet<E> extends Set<E> {
}
public interface NavigableSet<E> extends SortedSet<E> {
}
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>{
private transient NavigableMap<E,Object> m;
//外界使用无参构造创建TreeSet时,底层是使用无参构造创建的TreeMap
public TreeSet() {
this(new TreeMap<E,Object>());
}
//外界使用有参构造创建TreeSet时,底层是使用有参构造创建的TreeMap,并把外置比较器传入到TreeMap的内部
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
TreeSet(NavigableMap<E,Object> m) {
this.m = m;
}
//占位符
private static final Object PRESENT = new Object();
//TreeSet添加元素时,是使用到的TreeMap的put方法,并将元素存入Key中,value使用占位符占位
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
}
TreeSet<Student> set = new TreeSet<>();
TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
......
return 1;
}
});
set.add(new Student("天海翼", '女', 28, "2204", "001"));
set.add(new Student("天使萌", '女', 21, "2204", "002"));
set.add(new Student("水菜丽", '女', 25, "2204", "003"));
TreeSet底层由TreeMap实现