Java基础知识强化之集合框架笔记69:Collections类之ArrayList存储自自定义对象并排序的案例

1. ArrayList存储自自定义对象并排序的案例:

ArrayList存储自自定义对象,并使用Collections对ArrayList存储基本包装类的元素排序。

2. 代码实现:

(1)Student.java:

 1 package cn.itcast_02;
 2 
 3 /**
 4  * @author Administrator
 5  * 
 6  */
 7 public class Student implements Comparable<Student> {
 8     private String name;
 9     private int age;
10 
11     public Student() {
12         super();
13     }
14 
15     public Student(String name, int age) {
16         super();
17         this.name = name;
18         this.age = age;
19     }
20 
21     public String getName() {
22         return name;
23     }
24 
25     public void setName(String name) {
26         this.name = name;
27     }
28 
29     public int getAge() {
30         return age;
31     }
32 
33     public void setAge(int age) {
34         this.age = age;
35     }
36 
37     @Override
38     public int compareTo(Student s) {
39         int num = this.age - s.age;
40         int num2 = num == 0 ? this.name.compareTo(s.name) : num;
41         return num2;
42     }
43 }

(2)CollectionsDemo.java:

 1 package cn.itcast_02;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Comparator;
 6 import java.util.List;
 7 
 8 /*
 9  * Collections可以针对ArrayList存储基本包装类的元素排序,存储自定义对象可不可以排序呢?
10  */
11 public class CollectionsDemo {
12     public static void main(String[] args) {
13         // 创建集合对象
14         List<Student> list = new ArrayList<Student>();
15 
16         // 创建学生对象
17         Student s1 = new Student("林青霞", 27);
18         Student s2 = new Student("风清扬", 30);
19         Student s3 = new Student("刘晓曲", 28);
20         Student s4 = new Student("武鑫", 29);
21         Student s5 = new Student("林青霞", 27);
22 
23         // 添加元素对象
24         list.add(s1);
25         list.add(s2);
26         list.add(s3);
27         list.add(s4);
28         list.add(s5);
29 
30         // 排序
31         // 自然排序
32         // Collections.sort(list);
33         // 比较器排序
34         // 如果同时有自然排序和比较器排序,以比较器排序为主
35         Collections.sort(list, new Comparator<Student>() {
36             @Override
37             public int compare(Student s1, Student s2) {
38                 int num = s2.getAge() - s1.getAge();
39                 int num2 = num == 0 ? s1.getName().compareTo(s2.getName())
40                         : num;
41                 return num2;
42             }
43         });
44 
45         // 遍历集合
46         for (Student s : list) {
47             System.out.println(s.getName() + "---" + s.getAge());
48         }
49     }
50 }
原文地址:https://www.cnblogs.com/hebao0514/p/4866742.html