The individual compareTo() method of the Comparable elements cannot be overriden, unless one defines a separate subclass to Comparable and only applies the sorting to instances of that subclass.
For a generic Comparable type, overriding of the compare() method of the Comparator class on every sorting, provides access to the compareTo() method of the array components. Here is a quick implementation using Java inheritance and an option to do the sorting in ascending or descending order:
import java.util.Arrays;
import java.util.Comparator;
public class ArraySorter
{
private ArraySorter()
{
}
public static <T extends Comparable<T>> void sort(
final T[] array, final boolean ascending)
{
Arrays.sort(array, new Comparator<T>()
{
@Override
public int compare(T o1, T o2)
{
return (ascending?o1.compareTo(o2):o2.compareTo(o1));
}
});
}
public static void main(String[] args)
{
Integer[] intArray = {30,20,50,100,1,2,6,1,3,5};
System.out.println("UNSORTED: " + Arrays.asList(intArray));
ArraySorter.sort(intArray, true);
System.out.println("ASCENDING: " + Arrays.asList(intArray));
ArraySorter.sort(intArray, false);
System.out.println("DESCENDING: " + Arrays.asList(intArray));
}
}
Running the static sort() method above using the intArray value, as the main() method of the ArraySorter class does, the following output is produced:
UNSORTED: [30, 20, 50, 100, 1, 2, 6, 1, 3, 5]
ASCENDING: [1, 1, 2, 3, 5, 6, 20, 30, 50, 100]
DESCENDING: [100, 50, 30, 20, 6, 5, 3, 2, 1, 1]
Of course, the above result, for ascending order, is identical to just calling Arrays.sort(intArray).
java.util.Arraysclass and copy-paste the code of thesort(array, comparator)method.