创建TreeSet集合时,会默认对存储的元素进行排序。例如
TreeSet<Integer> set1 = new TreeSet<>();
set1.add(2);
set1.add(1);
set1.add(6);
set1.add(4);
for (Integer i : set1) {
System.out.println(i);
}
}
输出结果是:1 2 4 6,虽然元素是乱序添加的,但是会进行默认排序,此处是升序。
再例如:
TreeSet<String> set2 = new TreeSet<>();
set2.add("中文");
set2.add("bb");
set2.add("acc");
set2.add("%eer");
for (String i : set2) {
System.out.print(i+" ");
}
输出结果是:%eer acc bb 中文
但是如果存储的数据类型是实例化的对象,那么默认方法就无法进行比较,会导致创建失败。
以下是一个封装好的学生类
public class Student {
private String name;
private int age;
private double score;
public Student() {
}
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
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;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {//重写toString直接输出学生属性
return "姓名:" + name + ",年龄:" + age + ",分数:" + score;
}
}
用TreeSet直接存储该对象,实例化会失败,此时需要在实例化时,放入一个自定义比较器。
Student stu1 = new Student("张三", 19, 88);
Student stu2 = new Student("李四", 16, 87);
Student stu3 = new Student("王五", 18, 82);
Student stu4 = new Student("赵六", 20, 78);
Student stu5 = new Student("田七", 17, 98);
TreeSet<Student> stus = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student stu1, Student stu2) {
int num = -1;
if (stu2.getScore() - stu1.getScore() > 0) {//按照学生分数降序排列
num = 1;
}
return num;
}
});
stus.add(stu1);
stus.add(stu2);
stus.add(stu3);
stus.add(stu4);
stus.add(stu5);
for (Student i : stus) {//增强for循环遍历
System.out.println(i);
}
System.out.println("======================================");
Iterator<Student> it = stus.iterator();//迭代器遍历
while (it.hasNext()) {
Student stu = it.next();
System.out.println(stu);
输出结果如下:
姓名:田七,年龄:17,分数:98.0
姓名:张三,年龄:19,分数:88.0
姓名:李四,年龄:16,分数:87.0
姓名:王五,年龄:18,分数:82.0
姓名:赵六,年龄:20,分数:78.0