自定义比较器Comparator
package com.set;
import java.util.Comparator;
import com.bean.Person;
public class PersonComparatorByAgeAndName implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
int val = o1.getAge() - o2.getAge();
if (val == 0) {
return o1.getName().compareTo(o2.getName());
} else {
return val;
}
}
}
Comparable比较器
package com.exer;
public class Student implements Comparable<Student> {
private Integer no;
private String name;
private int score;
@Override
public int compareTo(Student o) {
int v = this.score - o.score;
return v == 0 ? this.no - o.no : v;
}
public Student() {
}
public Student(Integer no, String name, int score) {
this.no = no;
this.name = name;
this.score = score;
}
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return score + ", " + no + ", " + name;
}
}