//java中对ArrayList进行排序,比较器练习
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
//保存学生信息
class StudentInfo{
String name;
int age;
int score;
public StudentInfo(String name, int age , int score){
this.name = name;
this.age = age;
this.score = score;
}
}
class SortByAge implements Comparator{
public int compare(Object o1 , Object o2){
StudentInfo stu1 = (StudentInfo)o1;//向下转型
StudentInfo stu2 = (StudentInfo)o2;
//升序Ascending order
// return stu1.age - stu2.age;
//逆序Discending order
return stu2.age - stu1.age;
}
}
class SortByName implements Comparator{
public int compare(Object o1 , Object o2){
StudentInfo stu1 = (StudentInfo)o1;
StudentInfo stu2 = (StudentInfo)o2;
//字符串比较,按照字典序
//升序
return stu1.name.compareTo(stu2.name);
//降序
// return stu2.name.compareTo(stu1.name);
}
}
class SortByScore implements Comparator{
public int compare(Object o1 , Object o2){
StudentInfo stu1 = (StudentInfo)o1;
StudentInfo stu2 = (StudentInfo)o2;
//升序
return stu1.score - stu2.score;
//降序
// return stu2.score - stu1.score;
}
}
public class Main{
public static void main(String[] args){
List<StudentInfo> list = new ArrayList<StudentInfo>();
list.add(new StudentInfo("zhangsan" , 23 , 45));
list.add(new StudentInfo("lisi" , 32 , 53));
list.add(new StudentInfo("lisi" , 32 , 52));
list.add(new StudentInfo("wangwu" , 13 , 67));
list.add(new StudentInfo("zhengliu" , 27 , 43));
System.out.println("orginal:");
for(StudentInfo stu : list){
System.out.println("name :" + stu.name + "\tage :" + stu.age + "\tscore :" + stu.score);
}
Collections.sort(list, new SortByScore());
System.out.println("after sort:");
for(StudentInfo stu : list){
System.out.println("name :" + stu.name + "\tage :" + stu.age + "\tscore :" + stu.score);
}
}
}
比较器练习(list,set,map...)
最新推荐文章于 2023-03-20 21:58:19 发布