import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* 集合的排序可以使用集合的工具类Collections
* 该类封装了静态方法sort(),可以直接传入一个
* 集合,该排序只对list集合有效.要排序的类需要
* 实现Comparable接口,并重写compareTo()方法.
* 另外该方法还有一个重载的方法不需要实现该接口,
* 但需要在传入集合的时候同时传入一个自定义比较
* 器,在该自定义比较器中需要重写compare方法.
* @author Administrator
*
*/
public class ComparatorTest {
public static void main(String[] args) {
/*
* 创建一个存储学生信息的集合
*/
List<Student> list = new ArrayList<Student>();
/*
* 向集合中添加元素
*/
list.add(new Student("Andy",121501,80));
list.add(new Student("Jack",121504,70));
list.add(new Student("tomy",121503,60));
list.add(new Student("lucy",121505,75));
list.add(new Student("Rose",121502,90));
System.out.println("原集合:"+list);
/*
* 通过实现Comparable接口并重写compareTo()方法
*/
Collections.sort(list);
System.out.println("根据名字排序后的集合:"+list);
/*
* 通过重载方法,传入自定义比较器设置比较规则
*/
Collections.sort(list,new Comparator<Student>(){
public int compare(Student o1, Student o2) {
return o1.getStuId()-o2.getStuId();
}
});
System.out.println("按序号排序后的集合:"+list);
Collections.sort(list,new Comparator<Student>(){
public int compare(Student o1, Student o2) {
return o1.getGrade()-o2.getGrade();
}
});
System.out.println("按成绩排序后的集合:"+list);
}
}
/*
* 实现Comparable接口
*/
class Student implements Comparable<Student>{
private String name;
private int stuId;
private int grade;
public Student(){
}
public Student(String name, int stuId, int grade) {
super();
this.name = name;
this.stuId = stuId;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
/*
* 重写toString()方法
*/
public String toString(){
return "("+name+","+stuId+","+grade+")";
}
/*
* 重写compareTo()方法
* String类已重写compareTo()方法
* 可以直接调用其比较方法.
*/
public int compareTo(Student o) {
return this.name.compareTo(o.name);
}
}
集合排序
最新推荐文章于 2021-04-02 09:56:57 发布