- import java.util.Comparator;
- import java.util.TreeSet;
- public class Demo {
- public static void main(String[] args) {
- TreeSet<Student> set = new TreeSet<>(new Comparator<Student>(){
- @Override
- public int compare(Student o1, Student o2) {
- //1.先比较年龄
- int n1 = o1.age - o2.age;
- //2.再判断姓名
- int n2 = (n1 == 0 ? o1.name.compareTo(o2.name) : n1);
- return n2;
- }
-
- });
-
- set.add(new Student("张三",20));
- set.add(new Student("李四",19));
- set.add(new Student("赵七",28));
-
-
- set.add(new Student("赵七",28));//重复的元素;
-
- for(Student stu : set){
- System.out.println(stu.name + "--" + stu.age);
- }
- }
- }
复制代码 |
|