java对象数组排序,在Java中对对象数组进行排序

博客讨论了如何在Java中对包含JavaBean对象的数组进行排序,特别是根据Bean的整数属性值。作者提到当前代码仅比较字符串,并寻求帮助对整数值进行排序。解决方案建议让Project类实现Comparable接口,或者使用Arrays.sort()方法配合Comparator进行排序。
摘要由CSDN通过智能技术生成

I am working on a report module that shows the time spent and number of tasks. The values are set in the Java Bean and the bean object is stored in a array.I am using separate queries to get time and number of tasks.Now i have to sort the array based on time and number of tasks.

The code below compares only Strings:

if (!list.isEmpty()) {

Collections.sort(list, new Comparator() {

@Override

public int compare(Project p1, Project p2) {

return p1.getName().compare(p2.getName());

}

});

}

I have problems in sorting the integer value of a property in JavaBean which is stored in an array.Any help is greatly appreciated.

解决方案

In your comments below the question you say you have:

Project[] array = new Project[3];

If I were you I'd declare Project as

public class Project implements Comparable {

@Override

public int compareTo(Project other) {

return this.id - other.id; // or whatever property you want to sort

}

Then you can sort your array by simply calling

Arrays.sort(array);

If you don't want your class to implement the Comparable interface you can pass a comparator to Arrays.sort():

Arrays.sort(array, new Comparator() {

@Override

public int compare(Project o1, Project o2) {

return o1.id - o2.id; // or whatever property you want to sort

}

});

I used an anonymous one, you could also extract it to it's own class if needed elsewhere.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值