Comparator
自定义比较器,比较的对象本身不具有比较性
接口定义:
public interface Comparator<T>{
public int compare(T o1,T o2);
boolean equals(Object obj);
}
public class Student {//implements Comparable<Student>{
private String name;
private float score;
private int age;
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 float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return this.name+"--"+this.age+"--"+this.score;
}
public static void main(String[] args) {
List<Student> list=new ArrayList<Student>();
list.add(new Student("zhangsan",20,33f));
list.add(new Student("lisi",19,22f));
list.add(new Student("wangwu",22,99f));
list.add(new Student("sunzi",20,99f));
Collections.sort(list, new MyComparator());
for(Student s:list){
System.out.println(s.toString());
}
}
}
class MyComparator implements Comparator<Student>{
@Override
public int compare(Student s1, Student s2) {
if(s1.getScore()>s2.getScore()){
return -1;
}else if(s1.getScore()<s2.getScore()){
return 1;
}else{
if(s1.getAge()>s2.getAge()){
return -1;
}else if(s1.getAge()<s2.getAge()){
return 1;
}else{
return 0;
}
}
}
}
|
|