简体   繁体   中英

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 )

The dateDue has been formatted into an integer YYYYMMDD (From a calendar)

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. moduleDB being the Array List

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.

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> .

ps As mentioned in a previous post, you can also have your class implement the Comparator interface to achieve identical results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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