进阶day03-Collections里面的sort方法以及比较器Comparetor的使用

This commit is contained in:
2026-02-01 15:16:57 +08:00
parent 5ae936634a
commit c697420bc6
3 changed files with 52 additions and 2 deletions

View File

@@ -5,7 +5,6 @@ import java.util.Collections;
/* /*
- public static <T> void sort(List<T> list):将集合中元素按照默认规则排序。 - public static <T> void sort(List<T> list):将集合中元素按照默认规则排序。
- public static <T> void sort(List<T> listComparator<? super T> ):将集合中元素按照指定规则排序。
注意: 注意:
1.要使用以上的排序api,那么List集合的泛型的类型必须实现Comparable接口. 1.要使用以上的排序api,那么List集合的泛型的类型必须实现Comparable接口.

View File

@@ -0,0 +1,51 @@
package com.inmind.collections04;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/*
Comparable:自然排序功能
Comparator:比较器,给指定的集合,添加排序功能,它的优先级比自然排序要高
注意:当一个集合中保存的数据不具有自然排序功能或者对应拥有自然排序功能的类不满足你的需求时,
就使用直接使用比较器Comparator添加排序效果或者覆盖排序效果
- public static <T> void sort(List<T> listComparator<? super T> ):将集合中元素按照指定规则排序。
*/
public class Demo15 {
public static void main(String[] args) {
System.out.println("--------------对Integer默认集合排序整数的升序----------------");
ArrayList<Integer> lists1 = new ArrayList<>();
Collections.addAll(lists1, 1, 44, 23, 56, 32, 66, 12);
System.out.println(lists1);
//调用排序功
Collections.sort(lists1, new Comparator<Integer>() {//使用匿名内部类,创建了使用一次的比较器的实现类对象
/*
排序口诀:
我(o1)-它(o2):升序
它-我:降序
*/
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
System.out.println(lists1);
System.out.println("-------------------对自定义对象集合排序----------------------");
ArrayList<Student> lists3 = new ArrayList<>();
lists3.add(new Student("张三2", 19));
lists3.add(new Student("张三1", 18));
lists3.add(new Student("张三3", 20));
System.out.println(lists3);
//使用了比较器,覆盖了原本的自然排序功能
Collections.sort(lists3, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.age - o1.age;
}
});
System.out.println(lists3);
}
}

View File

@@ -53,7 +53,7 @@ public class Student implements Comparable<Student>{
if (this.age == o.age) { if (this.age == o.age) {
return this.id - o.id; return this.id - o.id;
} else { } else {
return this.age = o.age; return this.age - o.age;
} }
} }
} }