再美不及姑娘你
又见西风上碧树

需求:ArrayList存储学生对象,使用Collections进行排序,要求按年龄从大到小进行排序,年龄相同时按姓名的首字母排序

分析:

1.定义学生类

2.定义ArrayList集合对象

3.创建学生对象

4.将学生存储到集合中

5.对集合排序使用Collections

6.遍历集合

public class CollectionsDemo01 {
  public static void main(String[] args) {
      //创建ArrayList集合对象
      ArrayList<Student> al=new ArrayList<Student>();
      al.add(new Student("C三",18));
      al.add(new Student("张二",17));
      al.add(new Student("张四",19));
      al.add(new Student("Z三",18));
      //排序,需要指定comparator
      Collections.sort(al, new Comparator<Student>() {
          @Override
          public int compare(Student s1, Student s2) {
//               return 0;
              int num=s1.getAge()-s2.getAge();
              int num1= num==0?s1.getName().compareTo(s2.getName()):num;
              return num1;
          }
      });
      //遍历
      for (Student ss:al){
          System.out.println(ss.name+ss.age);
      }
  }
  public static class Student{
      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;
      }
  }
}

 

posted on 2022-04-01 17:40  再美不及姑娘你  阅读(319)  评论(0)    收藏  举报