欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-09 22:35:32
...

两种使用方法:
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());
        }

    }
}

相关标签: javase