Sorting an Array List of Objects based on a variable in object
arraylist, java, object, sorting
Solution
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>`.
p.s. As mentioned in a previous post, you can also have your class implement the `Comparator` interface to achieve identical results.
Problem
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.