java的比较器有两类,分别是Comparable接口和Comparator接口。
在为对象数组进行排序时,比较器就有非常大的作用
1、使用comparable接口,需要重写compareTo(T o)
方法,在其中定义排序规则,那么就可以直接调用java.util.Arrays.sort()来排序对象数组,
例子:
package com.yaoxun.test;
public class Student implements Comparable<Student> {
private int score;
private int age;
@Override
public int compareTo(Student o) {
if(this.score > o.score)
return 1;
else if(this.score < o.score)
return -1;
else {
if(this.age > o.age)
return 1;
else if(this.age < o.age)
return -1;
else
return 0;
}
}
}
compare(T o1, T o2)
方法,
package edu.sjtu.ist.comutil;
import java.util.Comparator;
class Student {
private String name;
private int age;
private float score;
public Student(String name, int age, float score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public String toString()
{
return name+"\t\t"+age+"\t\t"+score;
}
}
class StudentComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
if(o1.getScore()>o2.getScore())
return -1;
else if(o1.getScore()<o2.getScore())
return 1;
else{
if(o1.getAge()>o2.getAge())
return 1;
else if(o1.getAge()<o2.getAge())
return -1;
else
return 0;
}
}
}