对Java中的对象数组进行排序 [英] Sort an array of objects in Java
问题描述
我正在研究一个报告模块,该模块显示花费的时间和任务数量.这些值在Java Bean中设置,并且Bean对象存储在数组中.我正在使用单独的查询来获取时间和任务数量.现在我必须根据时间和任务数量对数组进行排序. 下面的代码仅比较字符串:
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<Project>() {
@Override
public int compare(Project p1, Project p2) {
return p1.getName().compare(p2.getName());
}
});
}
在对存储在数组中的JavaBean中的属性的整数值进行排序时,我遇到了问题.非常感谢您的帮助.
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];
如果我是你,我会声明Project
为
If I were you I'd declare Project
as
public class Project implements Comparable<Project> {
@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);
如果您不希望您的类实现Comparable
接口,则可以将比较器传递给Arrays.sort()
:
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<Project>() {
@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.
这篇关于对Java中的对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!