TreeMap和TreeSet都是有序的集合。
TreeSet要求集合中的元素实现Comparable接口,并实现compareTo方法进行比较,如果compareTo方法实现的不好,可能会导致元素插入失败,因为集合内部也通过compareTo方法来比较元素是否相等(而不是通过equals),即判断一个元素是否可插入。
TreeMap要求键列的元素实现Comparable接口,与TreeSet对元素的要求一样。
TreeSet其实内部是通过一个TreeMap来实现的,用了组合的设计模式。
我们来看下源码
/**
* The backing map.
*/
private transient NavigableMap<E,Object> m;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public TreeSet() {
this(new TreeMap<E,Object>());
}可以看到,在构造TreeSet时,也构造了一个TreeMap,并且Map中的value不使用。
我们调用TreeSet的add方法,其实是调用了TreeMap的put方法,我们再看一下源码。
publi

TreeMap和TreeSet基于Comparable接口实现元素排序,要求元素实现compareTo方法。TreeSet内部使用TreeMap,通过add方法调用TreeMap的put方法。Collections.sort()方法有两种使用方式:一种是传入实现了Comparable接口的List,另一种是传入Comparator接口子类型的实例定义排序规则。Collections是一个集合操作的工具类,提供静态方法处理各种集合。
最低0.47元/天 解锁文章
945

被折叠的 条评论
为什么被折叠?



