Final answer:
To sort integers in descending order, create a class called DescendingIntegerComparator that implements the Comparator interface. Implement the compare() method to sort numbers in reverse order. Use this comparator with List.sort to sort the list as desired.
Step-by-step explanation:
To sort a list of integers into descending order, you can create a class named DescendingIntegerComparator that implements the Comparator interface available in Java. The Comparator interface defines a comparison method called compare(). This method should return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
In the case of DescendingIntegerComparator, you’ll want to implement the compare() method such that it effectively inverts the result of the normal integer comparison. Here's how you can write this class:
import java.util.Comparator;
public class DescendingIntegerComparator implements Comparator {
public int compare(Integer num1, Integer num2) {
return num2.compareTo(num1);
}
}
When you use this comparator with the List.sort method, your list of integers will be sorted in descending order. For example, if you start with the list [2, 1, 4, 3], after sorting with this comparator, you will end up with the list [4, 3, 2, 1].
Here is how you might use the DescendingIntegerComparator in practice:
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class TestSort {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(4);
list.add(3);
Collections.sort(list, new DescendingIntegerComparator());
System.out.println(list); // Outputs [4, 3, 2, 1]
}
}