java comparable

本文介绍了一个使用Java Bean的示例,展示了如何通过实现Comparable接口来根据特定属性对对象数组进行排序。具体而言,示例中定义了StudentInfo类,并实现了compareTo方法以按grade属性排序,若grade相同则按age排序。

      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 ;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值