Set接口 [Collection】的子类
TreeSet
a.特点【无序,不可重复,查询快,可自动排序】,但需要指定排序规则,API中有一些类已经实现了Comparable接口],给出了默认排序规则,如:Integer:数值大小[升序] String:字典顺序等
b.指定排序规则方法:
一. 重写自然排序方法[compareTo]:
在对象类中实现implements Comparable接口<>
public class Demo1 {public static void main(String[] args) {TreeSet<Student> ts = new TreeSet<>();//8位二进制数为一个字节,一个中文两个字节//unicode值ts.add(new Student("zhangsan", 20));ts.add(new Student("lisi", 21));ts.add(new Student("wangwu", 22));ts.add(new Student("zhaoliu", 22));ts.add(new Student("zhaoqi", 22));for (Student student : ts) {System.out.println(student);}}
}class Student implements Comparable<Student> {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public Student() {}public String getName() {return name;}public void setName(String name) { this.name = name; }public int getAge() {return age;}public void setAge(int age) { this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}//自定义比较器时不用重写,调用父类的即可@Overridepublic int compareTo(Student o) {//主要条件比较年龄int result = this.getAge() - o.getAge();//z = (x > y) ? x : y;//年龄相同比较名字的英文顺序result= result ==0 ? this.getName().compareTo(o.getName()) :result;return result;//也可用if语句/*if(result==0){result=this.getName().compareTo(o.getName());}*/}
}打印结果:
----------------------------------------------------------
Student{name='zhangsan', age=20}
Student{name='lisi', age=21}
Student{name='wangwu', age=22}
Student{name='zhaoliu', age=22}
Student{name='zhaoqi', age=22}
**二.**自定义比较器:
在创建容器时使用有参构造,加入比接口对象new Comparator()
//采用匿名内部类或者lambda表达式重写compare方法
public class Demo2 {public static void main(String[] args) {//TreeSet<Student> ts = new TreeSet<>();TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {@Override//compare返回值为int类型,如果计算的类型不同则需要强转public int compare(Student1 o1, Student1 o2) {//主要条件int result = o1.getAge() - o2.getAge();//次要条件result=result==0?o1.getName().compareTo(o2.getName()):result;return result;}});//lambda表达式/*TreeSet<Student> ts = new TreeSet<>((o1, o2) -> {//主要条件 对年龄排序int result = o1.getAge() - o2.getAge();//次要条件 年龄相同,对名字排序result = result == 0 ? o1.getName().compareTo(o2.getName()) : result;return result;});*/ts.add(new Student("zhangsan", 20));ts.add(new Student("lisi", 21));ts.add(new Student("wangwu", 22));ts.add(new Student("zhaoliu", 22));ts.add(new Student("zhaoqi", 22));for (Student student : ts) {System.out.println(student);}}
}打印结果:
------------------------------------------------------------
Student{name='zhangsan', age=20}
Student{name='lisi', age=21}
Student{name='wangwu', age=22}
Student{name='zhaoliu', age=22}
Student{name='zhaoqi', age=22}
**三.**TreeSet底层实现思想【红黑树】
因为红黑树是有序的,所有TreeSet有排序功能