`

java comparable

阅读更多

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

}

}

 

}


 


二)输出结果:


lida_0  25 94
lida_1  23 95
lida_6  24 96
lida_7  20 97
lida_5  24 98
lida_3  22 99
lida_2  21 99
lida_4  22 100


三)小结

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;

}


compareTo  里指定了要进行比较的属性。如果不指定比较的属性,默认针对该bean的第一个字段进行排序;升序降序,只需指定 return  的value ;
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics