简体   繁体   English

根据对象中的变量对对象的数组列表进行排序

[英]Sorting an Array List of Objects based on a variable in object

I have an Array List of Objects 我有一个对象数组列表

The objects in the Array List are information for college called 'ModuleInfo' (course, assignments, dateDue ) 数组列表中的对象是大学信息,称为“ ModuleInfo”(课程,作业, dateDue

The dateDue has been formatted into an integer YYYYMMDD (From a calendar) dateDue已格式化为整数YYYYMMDD(来自日历)

I've looked at some of the other ways people have done this, but I can't get my head around what it is that I need to do. 我查看了人们执行此操作的其他方式,但是我无法确定我需要做什么。

Ideally because I've already stated when creating the Array List that it will contain 'ModuleInfo' objects I could just Collection.sort(moduleDB, ModuleInfo.getDateDue) or something along those lines. 理想情况下,因为我已经在创建数组列表时说过,它将包含“ ModuleInfo”对象,所以我可以只是Collection.sort(moduleDB,ModuleInfo.getDateDue)或类似的东西。 moduleDB being the Array List moduleDB是数组列表

Any help would be much appreciated. 任何帮助将非常感激。

If you want to use Collections.sort(List list) to sort your list, your object must implement the Comparable interface. 如果要使用Collections.sort(List list)Collections.sort(List list)进行排序,则您的对象必须实现Comparable接口。

public class ModuleInfo implements Comparable<ModuleInfo> {

    /* Your implementation */

    public int compareTo(ModuleInfo info) {
        if (this.dateDue < info.dateDue) {
            return -1;
        } else if (this.dateDue > info.dateDue) {
            return 1;
        } else {
            return 0;
        }
    }
}

Then call Collections.sort(moduleDB) where moduleDB has type ArrayList<ModuleInfo> . 然后调用Collections.sort(moduleDB) ,其中moduleDB类型为ArrayList<ModuleInfo>

ps As mentioned in a previous post, you can also have your class implement the Comparator interface to achieve identical results. ps如前一篇文章所述,您还可以让您的类实现Comparator接口以实现相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM