A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Java黑马 中级黑马   /  2015-7-4 17:46  /  477 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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;
}
}
}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马