Files
javaSE-0113/javaSE-day03/src/com/inmind/collections04/Demo15.java

52 lines
2.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
}
}