Student.java
package com.sxt.set3; /* * TreeSet:有序 * implements Comparable<Student> * 如果用内部比较器TreeSet必须是实现Comparable接口来实现有序 否则会出现报错:com.sxt.set4.Student cannot be cast to java.lang.Comparable * 使用泛型是为了在重写compareTo()方式时,object不用强制转换类型 */ //内部比较器:在类内重写比较规则即compareTo()方法 public class Student implements Comparable<Student> { private String name; private int age; private double salary; public Student(String name, int age, double salary) { super(); this.name = name; this.age = age; this.salary = salary; } public Student() { super(); } 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 getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", salary=" + salary + "]"; } //内部比较器之排序规则 按年龄 @Override public int compareTo(Student o) { return this.age - o.age; } }
TestStudent.java
package com.sxt.set3; /* * TreeSet */ import java.util.Set; import java.util.TreeSet; public class TestStudent { public static void main(String[] args) { Set<Student> arr = new TreeSet<>(); arr.add(new Student("bbb", 21, 532.2)); arr.add(new Student("ccc", 32, 32.2)); arr.add(new Student("ddd", 11, 352.2)); arr.add(new Student("aaa", 15, 32.2)); //遍历 for(Student s:arr){ System.out.println(s); } // 按照内部比较器按年龄排序结果: // Student [name=ddd, age=11, salary=352.2] // Student [name=aaa, age=15, salary=32.2] // Student [name=bbb, age=21, salary=532.2] // Student [name=ccc, age=32, salary=32.2] } }