比较器排序Comparator的使用

import java.util.Comparator;
import java.util.TreeSet;

/*比较器排序Comparator的使用
     实例:存储学生对象
     要求:年龄按照从小到大进行排序,当年龄相同是按照姓名的字母进行排序
* */
public class homework1 {
    public static void main(String[] args) {
        TreeSet<student> t=new TreeSet<student>(new Comparator<student>() {//匿名内部类
            @Override
            public int compare(student o1, student o2) {
                //return 0;
                int num= o1.getAge()-o2.getAge();
                int num2=num==0?o1.getName().compareTo(o2.getName()):num;
                return num2;
            }
        });
         student s1=new student("wangzhaojun",25);
         student s2=new student("diaochan",26);
         student s3=new student("yangyuhuan",30);
         student s4=new student("xishi",30);
        t.add(s1);
        t.add(s2);
        t.add(s3);
        t.add(s4);
        //遍历集合
        for(student a:t){
            System.out.println(a.getName()+","+a.getAge());
        }
    }
}

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

    public Student(String name, int age) {
        this.name = name;
        this.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;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值