|
Answer» An ArrayList is a collection of homogenous data types stored in contiguous memory locations. An ArrayList can be sorted using Collections.sort() method. This works fine as long as the ArrayList is made up of Strings. In case the ArrayList is made of custom object – Employee - in our case, we need to do a few more things - Create a class that implements the Comparator interface. This interface provides the compare() method which COMPARES two ARGUMENTS for order. It returns a negative integer if the first argument is less than second, zero if the two are equal, else a positive value. The inputs to this method will two employee objects that need to be compared. Inside the method write the logic to fetch the first name from the objects and compare them.
- In the Main class where theCollections.sort is called also pass the object of above-created class e.g. Collections.sort(<arraylist obj>, new <object of a class IMPLEMENTING comparator>)
- In case you want an option to sort theArrayList by first name or last name then you can create another class implementing Comparator which sorts the objects based on lastname. In the main method based on the preference, you can pass the desired comparator class in a sort method.
- Another way to sort theArrayList is to implement Comparable interface. This interface provides a compareTo() method which takes in an object to be compared as INPUT. Extend the Employee class to implement this interface and OVERRIDE the compareTo method to compare the objects based on the first name. As you can see, this approach is less flexible as compared to the one for using Comparator.
|