前几天写的那个是错误的,在这里将正确的更新。。。
通过实现ComParator接口,并且对Compare函数进行重写,自定义排序规则实现对ArrayList中对象的排序。。
Student类定义:
通过右键-》source-》自动生成Set和get方法
package first;
import java.util.Comparator;
import java.io.*;
public class Student implements Serializable,Comparator<Student> {
String id;
String name;
int score;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int result) {
this.score = result;
}
public void setAll(String id,String name,int score){
this.id=id;
this.name=name;
this.score=score;
}
public String toString(){
return (this.id+” “+this.name+” “+this.score);
}
@Override
public int compare(Student stu_1, Student stu_2) {
if (stu_1.score>stu_2.score)
return -1;
else
return 1;
}
}
应用:
ArrayList<Student> stuArray = new ArrayList<Student>();
Collections.sort(stuArray, new Student());
这样就实现了排序