I've been relearning Java after a long time, and I'm trying out writing some sorting algorithms. The (rather outdated) textbook I have uses the Comparable interface to sort objects. Since Comparables are now generic types, doing this gives me a lot of warnings about raw types when compiling. After some research, it looks like I can do something like, for example:
public class Sorting
{
public static <T extends Comparable<T>> void quickSort(T[] list, int start, int end)
{
/*...*/
while((list[left].compareTo(list[pivot]) < 0) && (left != right)) // for example
left++;
/*...*/
}
}
The problem with this is that the naive way of calling this method does not work:
public class SortingTest
{
public static void main(String[] args)
{
// Produces an error, cannot create arrays of generic types
Comparable<Integer>[] list = new Comparable<Integer>[100];
/* fill the array somehow */
Sorting.quickSort(list, 0, 99);
}
}
It is illegal to create an array of generic types in Java. The problem only gets worse if I try to implement a merge sort, since that requires creating arrays of Comparable types inside the merge sort method itself.
Is there any way to handle this situation elegantly?
<T extends Comparable<? super T>>