Arrays 的sort 可以实现简单的排序,如果想对java bean 指定属性字段,或者是多个字段进行比较排序,我自己研究了一下comparable,可以实现指定bo属性的排序。
一)代码
package cn.com.ld.bo;
import java.util.Arrays;
public class StudentInfo implements Comparable {
private String name;
private int age;
private int grate;
private StudentInfo(String name, int age, int grate) {
this.name = name;
this.age = age;
this.grate = grate;
}
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;
}
public int getGrate() {
return grate;
}
public void setGrate(int grate) {
this.grate = grate;
}
public int compareTo(Object o) {
int other_grate = ((StudentInfo) o).getGrate();
int other_age = ((StudentInfo) o).getAge();
int result = 0;
if (this.grate > other_grate) {
result = 1;
} else if (this.grate < other_grate) {
result = -1;
} else{
result = (this.age - other_age) > 0 ? -1 : 1 ;
}
return result;
}
public static void main(String[] args) {
StudentInfo[] siArray = new StudentInfo[] {
new StudentInfo("lida_0", 25, 94),
new StudentInfo("lida_1", 23, 95),
new StudentInfo("lida_2", 21, 99),
new StudentInfo("lida_3", 22, 99),
new StudentInfo("lida_4", 22, 100),
new StudentInfo("lida_5", 24, 98),
new StudentInfo("lida_6", 24, 96),
new StudentInfo("lida_7", 20, 97), };
Arrays.sort(siArray);
for (StudentInfo studentInfo : siArray) {
System.out.println(studentInfo.name + " " + studentInfo.age + " "
+ studentInfo.grate);
}
}
}
public int compareTo(Object o) {
int other_grate = ((StudentInfo) o).getGrate();
int other_age = ((StudentInfo) o).getAge();
int result = 0;
if (this.grate > other_grate) {
result = 1;
} else if (this.grate < other_grate) {
result = -1;
} else{
result = (this.age - other_age) > 0 ? -1 : 1 ;
}
return result;
}