5

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.