https://www.cnblogs.com/yinq/p/6926581.html
List排序大體上分為如下兩類:
1、List<Integer> 對Integer、String等類型的List排序
2、List<Object> 對自定義對象的排序
本文代碼例子只進(jìn)行簡單的介紹代态,僅起到拋磚引玉作用绒尊,讀者可以自行開發(fā)哈。
1灵汪、對List<Integer>進(jìn)行排序
代碼如下:
1 List<Integer> l = new ArrayList<Integer>();
2 l.add(3);
3 l.add(1);
4 l.add(2);
5 l.add(9);
6 l.add(7);
7
8 Collections.sort(l);//默認(rèn)排序(從小到大)
9 for(int i : l){
10 System.out.println(i);
11 }
12
13 Collections.reverse(l);//倒敘(從大到小)
14 for(int i : l){
15 System.out.println(i);
16 }
1 /*
2 * 學(xué)生實(shí)體
3 */
4 class Student implements Comparable<Student>{
5 public Integer Age = 0;
6 public String Name = "";
7
8 public Integer getAge() {
9 return Age;
10 }
11 public void setAge(int age) {
12 Age = age;
13 }
14
15 public String getName() {
16 return Name;
17 }
18 public void setName(String name) {
19 Name = name;
20 }
21
22 public Student(int age,String name){
23 this.Age = age;
24 this.Name = name;
25 }
26
27 @Override
28 public int compareTo(Student s) {
29 //自定義比較方法,如果認(rèn)為此實(shí)體本身大則返回1柑潦,否則返回-1
30 if(this.Age >= s.getAge()){
31 return 1;
32 }
33 return -1;
34 }
35 }