Sorting Submissions
Suppose we have a collection of submissions. We want to sort the submissions according to their "natural ordering".
Natural ordering, here, means the default ordering of objects of a specific type when they are sorted in an array or a collection.
For example, the natural ordering of String
objects is alphabetic order. The natural ordering of Date
objects is chronological order.
Java allows you to define the natural ordering of objects of a specific type by implementing Comparable
interface.
A class that implements the Comparable
interface is said to have natural ordering. And, the compareTo()
method is called the natural comparison method.
So the natural ordering of Submission
is based on the order they were received, as it is defined in the Submission.compareTo
method.
If we instantiate several objects of type Submission
and store them in a Java Collection such as a List
, then we can use Collections.sort
to order (sort) the submissions based on their natural ordering.
An example is provided in the Main.java
in the demo
package of the starter code.
List<String> students = getStudents();
List<Submission> submissions = getSubmissions(students);
System.out.print("Submission sorted (natural ordering):");
Collections.sort(submissions);
System.out.println(submissions);