通过比较器实现比较规则

通过比较器实现比较规则时,我们需要单独创建一个比较器,比较器需要实现 Comparator 接口中的 compare 方法来定义比较规则。在实例化 TreeSet 时将比较器对象交给 TreeSet 来完成元素的排序处理。此时元素自身就不需要实现比较规则了。

创建Student类

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

    public Student(){}

    @Override
    public String toString(){
        return "Student{" +
                "name='" + name + '\'' +
                ",age=" + age +
                '}';
    }

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

    @Override
    public boolean equals(Object o){
        if(this == o) return true;
        if(o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        if(age != Student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }

    @Override
    public int hashCode(){
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}

创建比较器:

public class StudentComparator implements Comparator<Student>{
    //定义比较规则
    @Override
    public int Compare(Student o1,Student o2){
        if(o1.getAge() > o2.getAge()){
            return 1;
        }
        if(o1.getAge() == o2.getAge()){
            return o1.getName().compareTo(o2.getName());
        }
        return -1;
    }
}
public class TreeSetTest3 {
    public static void main(String[] args){
        //创建TreeSet容器,并给定比较器对象
        Set<Student> set = new TreeSet<>(new StudentComparator());
        Student s = new Student("小明",18);
        Student s1 = new Student("小红",22);
        Student s2 = new Student("小亮",22);
        set.add(s);
        set.add(s1);
        set.add(s2);
        for(Student student : set){
            System.out.println(student);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值