TreeSet排序
TreeSet中的对象是按 一定的顺序排列的 它的底层就是TreeMap 当去new一个TreeSet对象时 实际上调用TreeMap构造器 常用的构造方法一般有两种.
一是 使用无参构造器:
public class TreeSet_ {
public static void main(String[] args) {
TreeSet<String> strings = new TreeSet<>(); //无参构造器创建对象
strings.add("no4"); //添加对象进 TreeSet集合中
strings.add("no1");
strings.add("no3");
System.out.println(strings);
}
}
//输出
[no1, no3, no4]
可以看到TreeSet集合中的顺序与我们的添加顺序不同 它按照了一定的顺序排列. 当我们使用无参构造器创建这个集合时 因为我添加对象的类型为String 所以添加元素时调用了Comparable 接口中的compareTo() 方法按照字符串的大小排序
从以上的类图中可以看到String 实现了Comparable接口 如果传入的对象类型 没有实现Comparable接口.
@Test
public void m() {
TreeSet<Person> peoples = new TreeSet<>(); //添加元素类型为Perosn
peoples.add(new Person("赵日天", 20));
peoples.add(new Person("叶良辰", 21));
}
}
class Person { //该类没有实现Comparable接口
public Person(String name, int age) {
this.name = name;
this.age = age;
}
String name;
int age;
}
当运行以上代码时 程序会报错 产生异常 其本质是 TreeSet底层 TreeMap 集合中是不能有相同元素的, 判断元素是否相同 根据比较(元素的大小) ,而添加的Person对象中 并没有提供比较大小的方法.
二 有参构造器
TreeSet 有参构造器 传入一个Comparator 的比较器
@Test
public void m() {
//传入一个Comparator匿名对象 重写实现compare方法排序去重
TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) { //按字符串长度比较
return o1.length() - o2.length();
}
});
treeSet.add("no1");
treeSet.add("no");
treeSet.add("no22");
treeSet.add("hello,world");
System.out.println(treeSet);
}
//输出
[no, no1, no22, hello,world]
使用有参构造器 传入Comparator比较器接口 可实现自定义定序排序. 具体排序方式根据重写的compara方法而定.