学习博客:TreeSet的比较器排序

两种使用方法:
TreeSet hs=new TreeSet(new MyCoparator());
这个需要自己写类,我给出相应代码`

package cn.setdemo_02;

import java.util.Comparator;

public class MyCoparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        int num=o1.getAge()-o2.getAge();
        int num2=num==0?o1.getName().compareTo(o2.getName()):num;
        return num2;
    }
}

学生方法:

package cn.setdemo_02;

import java.util.Objects;

public class Student  {
    private  int age;
    private  String name;


    public Student(String name, int age) {
        this.age = age;
        this.name = name;
    }

    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;
    }

}


第二种:直接在主方法里面定义内部类`

 TreeSet<Student> hs=new TreeSet<Student>(new Comparator<Student>() {
           @Override
           public int compare(Student o1, Student o2) {
             int num=o1.getAge()-o2.getAge();
              int num2=num==0?o1.getName().compareTo(o2.getName()):num;            return num2;
           }

主方法我放这了:

package cn.setdemo_02;

import sun.reflect.generics.tree.Tree;

import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class SetDemo {
    public static void main(String[] args) {
//        TreeSet<Student> hs=new TreeSet<Student>(new Comparator<Student>() {
//            @Override
//            public int compare(Student o1, Student o2) {
//               int num=o1.getAge()-o2.getAge();
//               int num2=num==0?o1.getName().compareTo(o2.getName()):num;
//               return num2;
//            }
//        });//这个用于一次性使用
        TreeSet<Student> hs=new TreeSet<Student>(new MyCoparator());
        //这个用于多次使用
        hs.add(new Student("zsp",20));
        hs.add(new Student("wlx",22));
        hs.add(new Student("lfl",21));
        hs.add(new Student("wlx",20));
        hs.add(new Student("lfl",21));
        hs.add(new Student("jxf",22));
        hs.add(new Student("qax",22));
        for (Student s:hs)
        {
            System.out.println(s.getName()+"----"+s.getAge());
        }

    }
}

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页