一、HashSet&LinkHashSet
二、TreeSet
排序方式:
第一种排序方式
总结
使用场景:
TreeSet代码示例
package MySet;
import java.util.TreeSet;
public class TreeSetDemo1 {
public static void main(String[] args) {
/*
需求:创建5个学生对象
属性:(姓名,年龄,语文成绩,数学成绩,英语成绩),
按照总分从高到低输出到控制台
如果总分一样,按照语文成绩排
如果语文一样,按照数学成绩排
如果数学一样,按照英语成绩排
如果英语一样,按照年龄排
如果年龄一样,按照姓名的字母顺序排
如果都一样,认为是同一个学生,不存。
第一种:默认排序/自然排序
第二种:比较器排序
默认情况下,用第一种排序方式
*/
//1.创建学生对象
Student s1 = new Student("zhangsan",23,90,99,50);
Student s2 = new Student("lisi",24,90,97,50);
Student s3 = new Student("wangwu",25,95,100,30);
Student s4 = new Student("zhaoliu",26,60,99,70);
Student s5 = new Student("qianqi",26,70,80,70);
//2.创建集合
TreeSet<Student> ts = new TreeSet<>();
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
for (Student t : ts) {
System.out.println(t);
}
}
}
package MySet;
public class Student implements Comparable<Student> {
private String name;
private int age;
private int chinese;
private int math;
private int english;
public Student(String name, int age, int chinese, int math, int english) {
this.name = name;
this.age = age;
this.chinese = chinese;
this.math = math;
this.english = english;
}
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 int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", chinese=" + chinese +
", math=" + math +
", english=" + english +
'}';
}
@Override
public int compareTo(Student o) {
int sum1 = this.getChinese() + this.getEnglish() + this.getMath();
int sum2 = o.getChinese() + o.getEnglish() + o.getMath();
//比较两者的总分
int i = sum1 - sum2;
//如果总分一样就按照语文成绩排序
i = i == 0 ? this.getChinese() - o.getChinese() : i;
//如果语文一样就按照数学成绩排序
i = i == 0 ? this.getMath() - o.getMath() : i;
//如果数学一样就按照英语成绩排序
i = i == 0 ? this.getEnglish() - o.getEnglish() : i;
//如果英语一样就按照年龄排序
i = i == 0 ? this.getAge() - o.getAge() : i;
//如果年龄一样就按照姓名的字母顺序排序
i = i == 0 ? this.getName().compareTo(o.getName()) : i;
return i;
}
}