//比较器排序 import java.util.Comparator; import java.util.TreeSet;

public class Demo07 { public static void main(String[] args) { //比较器排序 TreeSet set = new TreeSet<>(new Comparator() { @Override public int compare(Student o1, Student o2) { int result = o1.getAge() - o2.getAge(); if (result == 0) { result = o1.getName().compareTo(o2.getName()); } return result; } });

    set.add(new Student("zhangsan", 24));
    set.add(new Student("lisi", 18));
    set.add(new Student("wangwu", 24));
    set.add(new Student("zhaoliu", 24));
    set.add(new Student("chenglong", 58));

    //遍历集合
    for (Student student : set) {
        System.out.println(student);
    }
}

}

//自然排序 class Student implements Comparable{ private String name; private int age;

public Student() {
}

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

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

@Override
public int compareTo(Student o) {
    int result = this.age - o.age;
    if (result == 0) {
        result = this.name.compareTo(o.name);
    }
    return result;
}
07、分析以下需求并完成代码 使用TreeSet存储学生对象按照年龄进行升序排列如果年龄相同按照姓名首字母字典排序 分别使用自然排序和比较器排序两种方式实现学生信息如下 new Studentzhangsan 24; new Studentlisi 18; new Studentwangwu 24;

原文地址: https://www.cveoy.top/t/topic/cJTy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录