Comparable接口
import java.util.Arrays;
public class LocalTest{
public static void main(String[] args){
Student[] sa = {new Student("z1", 17, 99), new Student("z2", 19, 98),
new Student("z3", 20, 100), new Student("z4", 2, 98)};
Arrays.sort(sa);
for(Student s : sa){
System.out.println(s.toString());
}
}
}
class Student implements Comparable{
public String name;
public int age;
public int score;
public Student(String name, int age, int 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;
}
@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;
}
}
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score
+ "]";
}
}
结果:
Student [name=z3, age=20, score=100]
Student [name=z1, age=17, score=99]
Student [name=z4, age=2, score=98]
Student [name=z2, age=19, score=98]
说明:按照
分数从高到低,分数相等时按年龄从低到高的顺序排列。而Arrays.sort()默认按从小到大的顺序排列。所以A.compareTo(B)方法中返回1表示大于,即该对象A相对于对象B在该数组中排在B后面。所以
返回1时就表示把A排在B后面。
因此,
按分数从高到低排列,要把分数低的对象排在后面,所以就有当A分数低于B时返回1。
比较器的排序原理
Comparator比较器
import java.util.Arrays;
import java.util.Comparator;
public class Test2{
public static void main(String args[]){
StudentScore[] ss = {new StudentScore("z3",23,105),new StudentScore("z1",22,101),new StudentScore("z2",20,105),new StudentScore("z4",22,104)};
Arrays.sort(ss, new StudentCmp());
for(StudentScore s : ss){
System.out.println(s);
}
}
}
/*对象比较类,按分数从高到低,分数相等时按年龄从低到高排列*/
class StudentCmp implements Comparator{
@Override
public int compare(StudentScore o1, StudentScore o2) {
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;
}
}
}
}
class StudentScore{
private int score;
private int age;
private String name;
public StudentScore(String name, int age, int score){
this.name = name;
this.age = age;
this.score = score;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "StudentScore [name=" + name + ", age=" + age + ", score="
+ score + "]";
}
}输出:
StudentScore [name=z2, age=20, score=105]
StudentScore [name=z3, age=23, score=105]
StudentScore [name=z4, age=22, score=104]
StudentScore [name=z1, age=22, score=101]
从程序结果可以发现,Comparable和Comparator两个接口都可以实现相同的功能,但与Comparable相比Comparator接口明显是一种补救的做法。所以,建议使用Comparable接口进行排序操作比较方便。