so earlier this year I was given an assignment at university. The assignment was to create a Car park management system by using OOP procedures. For example, we learnt how to use inheritance, abstract classes and instances. I have already completed and passed this assignment so this question is just for knowledge purposes. One of the tasks was to order the ArrayList of objects in chronological order. To do this, we was taught the comparable/comparator way. However, I could not get my head around it and was unable to do it. The problem was, we had to order a ‘DateTime’ object which was in a ‘Vehicle’ object in the arraylist. I am not using a predefined libary for the date and time as it needed to be user entered. Thanks.

Here is where I am trying to sort the arraylist. I understand that it’s not working because the Arraylist is an Arraylist of object vehicles. I don’t understand how I would sort the object using comparable or comparator. Any help would be appericated.

You want to compare Vehicles. So you’ll need a VehicleComparator, not a DateTime comparator:

public class VehicleComparator implements Comparator {
@Override
public int compare(Vehicle o1, Vehicle o2) {
// now get the two vehicle's dates and compare them
}
}

Then

Collections.sort(vehicles, new VehicleComparator());

Update:

Also, you don’t need a Comparator AND a Comparable .

A Comparator is a standalone class to compare things. You use that to call Collections.sort(vehicles, comparator) .

Alternatively you can make things implement Comparable themselves (e.g. Vehicle implements Comparable ). Then they can effectively compare themselves. If something implements Comparable (this is known as “natural ordering”). When doing it this way, you can call Collections.sort(vehicles) . That version of the sort method expects everything in the list to implement Comparable , and so doesn’t need a standalone Comparator to do that work for it.