TreeSet使用上总体上与HashSet相同,不同的是TreeSet会对元素进行排序,向TreeSet中添加元素花的时间比HashSet稍长,但TreeSet添加/搜索/修改/删除元素的复杂度是稳定的log(n)
TreeSet使用示例
public static void main(String[] args) {
TreeSet<String> sorter = new TreeSet<>();
sorter.add("Bob");
sorter.add("Amy");
sorter.add("David");
sorter.add("Carl");
for (String s : sorter) {
System.out.println(s);
}
}
该程序会输出
Amy
Bob
Carl
David
TreeSet由TreeMap实现
向TreeSet中添加的元素应该实现Comparable接口
如果要添加的元素没有实现该接口或者想用其他方式比较,可以在构造TreeSet时提供一个实现了Comparator的对象
public interface Comparator<T>
{
int compare(T a, T b);
}
TreeSet实现了SortedSet(需要在构造时传入比较器才能真正使用)与NavigableSet接口