s-day03--比较器Comparetor的使用

This commit is contained in:
xx
2026-10-15 10:15:14 +08:00
parent bc989fad33
commit 196c293950
@@ -0,0 +1,35 @@
package com.inmind.colletions04;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/*
18.比较器Comparetor的使用
static <T> void sort(List<T> list, Comparator<? super T> c) 根据指定的比较器引起的顺序对指定的列表进行排序。
当集合中保存的数据不具有自然排序功能或者它原本的自然排序功能不满足我们的需求,就可以使用比较器来添加或者覆盖排序效果
*/
public class Demo14 {
public static void main(String[] args) {
ArrayList<Integer> lists = new ArrayList<>();
Collections.addAll(lists, 11, 2, 33, 444, 5, 15);
System.out.println(lists);
Collections.sort(lists);
System.out.println(lists);
/*
static <T> void sort(List<T> list, Comparator<? super T> c) 根据指定的比较器引起的顺序对指定的列表进行排序。
*/
//对整数进行降序排序,舍弃掉默认的自然排序功能
Collections.sort(lists, new Comparator<Integer>() {//匿名内部类
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;//自动拆箱
}
});
System.out.println(lists);
//请大家创建一个保存学生对象的集合,并按学生的年龄升序排序,要求使用比较器
}
}