TreeSet基本特点
1.元素是有序的
2.不能存储重复的元素
TreeSet类存储自定义对象
package MONA.demo06_treeset;
import java.util.Set;
import java.util.TreeSet;
/**
* TreeSet
* 1.元素是有序的(按照自然排序)
* 2.不能存储重复元素
*/
public class Demo01 {
public static void main(String[] args) {
TreeSet treeSet = new TreeSet();
treeSet.add("bbb");
treeSet.add("ccc");
treeSet.add("aaa");
treeSet.add("ddd");
treeSet.add("ddd");
System.out.println(treeSet);
}
}
使用自然排序(Comparable)接口
package MONA.demo06_treeset;
import java.util.TreeSet;
/**
* TreeSet 存储自定义对象
*
* ClassCastException:类型转换异常
*
* 需要告诉TreeSet在存储自定义对象时,
* 应该按照什么来排序
*
* 自定义的对象需要实现接口:Comarable
* 实现接口的抽象方法:comparaTo
* 在compateTo里面编写排序的规则
* compateTo方法可以返回三种类型的值:
* 小于0
* 等于0
* 大于0
*
* 根据年龄进行比较,按照年龄进行排序
*/
public class Demo02 {
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<>();
treeSet.add(new Student("李四",20));
treeSet.add(new Student("赵六",33));
treeSet.add(new Student("王五",21));
treeSet.add(new Student("田七",30));
treeSet.add(new Student("小刘",30));
System.out.println(treeSet);
}
}
class Student implements Comparable<Student>{
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
// System.out.println(this.name);
// System.out.println(o.name);
// System.out.println("-------------------");
//按照姓名排序
//按照年龄排序:
//升序 return this.age - o.age;
//降序 return o.age - this.age;
//问题:如果年龄相同,那么会覆盖
//先按照年龄进行排序,如果年龄相同则按照姓名排序
//姓名和年龄都相同,那么不添加
int i = this.age - o.age;
return i == 0 ? this.name.compareTo(o.name) : i;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
通过构造方法传入排序比较器
package MONA.demo06_treeset;
import java.util.Comparator;
import java.util.TreeSet;
public class Demo03 {
public static void main(String[] args) {
// Comparator comparator = new Comparator() {
// @Override
// public int compare(Object o1, Object o2) {
// //按照年龄排序
// return 1;
// }
// };
Comparator comparator =new Comparator<Teacher>(){
@Override
public int compare(Teacher o1, Teacher o2) {
int i = o1.age - o2.age;//升序
return i == 0? o1.name.compareTo(o2.name) : i;
}
};
//通过构造方法传入排序比较器
TreeSet<Teacher> treeSet = new TreeSet<>(comparator);
treeSet.add(new Teacher("老李",55));
treeSet.add(new Teacher("老王",30));
treeSet.add(new Teacher("小王1",25));
treeSet.add(new Teacher("小王2",25));
System.out.println(treeSet);
TreeSet<Teacher> teachers2 = new TreeSet<>(new Comparator<Teacher>(){
@Override
public int compare(Teacher o1, Teacher o2) {
int i = o1.age - o2.age;//升序
return i == 0? o1.name.compareTo(o2.name) : i;
}
});
}
}
class Teacher{
String name;
int age;
public Teacher(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}