(JAVA)用TreeSet集合存储学生类对象并按照年龄排序(方法二)

方法一见上一篇博客
题目要求:
1.用TreeSet存储学生对象,并遍历,创建集合使用无参构造;
2.按照年龄从小到大排序,年龄相同时,按照姓名的字母排序 。
这里也可以用匿名内部类实现,而不必在学生类中重写compareTo方法。实现程序如下:

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

public class TreeSetDemo3 {
    
    
    public static void main(String[] args) {
    
    
        TreeSet<Stu> treeSet = new TreeSet<Stu>(new Comparator<Stu>() {
    
    
            @Override
            public int compare(Stu s1, Stu s2) {
    
    
                int num = s1.getAge() - s2.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                return num2;
            }
        });//使用匿名内部类实现带参构造

        //创建学生对象
        Stu s1 = new Stu("ZhangSan",18);
        Stu s2 = new Stu("LiSi",19);
        Stu s3 = new Stu("WangWu",20);
        Stu s4 = new Stu("ZhaoLiu",18);

        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);

        //增强for遍历
        for(Stu s:treeSet){
    
    
            System.out.println(s.getName()+" , "+s.getAge());
        }

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45727931/article/details/108351602