s-day02-比较器Comparetor的使用
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
package com.inmind.collections04;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
|
||||
/*
|
||||
比较器Comparetor的使用
|
||||
static <T> void sort(List<T> list, Comparator<? super T> c) 根据指定的比较器引起的顺序对指定的列表进行排序。
|
||||
|
||||
当集合中保存的数据不具有自然排序功能或者它原本的自然排序功能不满足我们的需求,就可以使用比较器来添加或者覆盖排序效果
|
||||
|
||||
*/
|
||||
public class Demo15 {
|
||||
public static void main(String[] args) {
|
||||
//创建保存狗的集合
|
||||
ArrayList<Dog> dogs = new ArrayList<>();
|
||||
dogs.add(new Dog("小黄", 3));
|
||||
dogs.add(new Dog("小白", 5));
|
||||
dogs.add(new Dog("小黑", 2));
|
||||
System.out.println(dogs);
|
||||
//希望按照狗的年龄排序
|
||||
//static <T> void sort(List<T> list, Comparator<? super T> c) 根据指定的比较器引起的顺序对指定的列表进行排序
|
||||
Collections.sort(dogs, new Comparator<Dog>() {
|
||||
@Override
|
||||
public int compare(Dog o1, Dog o2) {
|
||||
//return o1.age-o2.age;//升序:我-它
|
||||
return o2.age-o1.age;//降序:它-我
|
||||
}
|
||||
});
|
||||
System.out.println(dogs);
|
||||
System.out.println("-----------------以下是对有排序功能的覆盖--------------------");
|
||||
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));
|
||||
Collections.sort(students, new Comparator<Student>() {
|
||||
@Override
|
||||
public int compare(Student o1, Student o2) {
|
||||
return o1.score - o2.score;//升序
|
||||
}
|
||||
});
|
||||
System.out.println(students);
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user