s-day02-Collections里面的sort方法以及Comparable接口

This commit is contained in:
2026-08-02 14:34:10 +08:00
parent 3cb9b35ade
commit fc1ab55c40
2 changed files with 78 additions and 0 deletions
@@ -0,0 +1,39 @@
package com.inmind.collections04;
import java.util.ArrayList;
import java.util.Collections;
/*
static <T extends Comparable<? super T>> void sort(List<T> list) 根据其元素的自然排序,按照升序排列指定的列表。
*/
public class Demo14 {
public static void main(String[] args) {
//整数的自然排序,默认升序
ArrayList<Integer> lists = new ArrayList<>();
Collections.addAll(lists, 111, 22, 32, 4, 555);
System.out.println(lists);
//对集合进行排序
Collections.sort(lists);
System.out.println(lists);
System.out.println("-------------------------------------");
//字符串的默认排序,按照字典排序,按ASCII码值
ArrayList<String> strs = new ArrayList<>();
Collections.addAll(strs, "ab", "ba", "aa", "ca", "ac","bb");
System.out.println(strs);
//对集合进行排序
Collections.sort(strs);
System.out.println(strs);
//自定义类的排序(Student)
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("张三1", 18,88));
students.add(new Student("张三2", 18,90));
students.add(new Student("张三3", 18,93));
students.add(new Student("张三4", 18,39));
System.out.println(students);
//注意:Collections.sort排序时,传入的集合的内容,必须拥有自然排序功能(实现Comparable)
Collections.sort(students);
System.out.println(students);
}
}
@@ -0,0 +1,39 @@
package com.inmind.collections04;
public class Student implements Comparable<Student>{
String name;
int age;
int score;
public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", score=" + score +
'}';
}
/*
排序口诀:
我(this)-它(参数o):升序
它-我:降序
*/
@Override
public int compareTo(Student o) {
// return this.score - o.score; //升序
/* if (this.score > o.score) {
return -1;
} else if (this.score < o.score) {
return 1;
} else {
return 0;
}*/
return o.score - this.score;
}
}