package com.javabase.obj.comparator;
import java.util.Comparator;
/**自定義比較器类,用於比較學生的成績,定義的時候一定要給泛型
* @author Administrator
*
*/
public class Compared implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
//定義規則
if (o1.getCore()>o2.getCore()) {
return 1;
} else if(o1.getCore()<o2.getCore()){
return -1;
}
return 0;
}
}
//学生类,比较的对象
package com.javabase.obj.comparator;
import java.util.ArrayList;
import java.util.Collections;
/**比較的對象類
* @author Administrator
*
*/
public class Student {
//姓名
private String name;
//班級
private String glass;
//成績
private double core;
public Student() {
super();
}
public Student(String name, String glass, double core) {
super();
this.name = name;
this.glass = glass;
this.core = core;
}
public String getName() {
return name;
}
public String getGlass() {
return glass;
}
public double getCore() {
return core;
}
@Override
public String toString() {
return this.name+"--"+this.glass+""+this.core;
}
//測試比較器的方法
public static void main(String[] args) {
//創建一個集合
ArrayList< Student> list=new ArrayList<Student>();
// /添加元素
list.add(new Student("zhangsan","三班",60));
list.add(new Student("李四","三班",60));
list.add(new Student("王二","三班",80));
list.add(new Student("碼子","三班",68));
list.add(new Student("狗蛋","三班",80));
list.add(new Student("水哥","三班",40));
//沒有使用比較器的時候是亂序的
// for (Student stu : list) {
// System.out.println(stu);
// }
//使用比較器進行輸出,list是比較的集合,後面的對象是定義的比較器
Collections.sort(list,new Compared());
for (Student stu : list) {
System.out.println(stu);
}
}
}