Generics and sorting in Java

peninha picture peninha · Jan 15, 2010 · Viewed 9.2k times · Source

Suppose you write a static function in Java to sort an array, much like Arrays.sort(). The problem with Arrays.sort() is that it receives an array of Object, and throws a ClassCastException if its elements don't implement Comparable.

So you want your function to receive as an argument an array of a subtype of Comparable. Something like that could work:

static <T extends Comparable> void sort(T[] array);

The problem with that signature is that you can still pass an array of Comparables with Integers and Strings for instance, which would cause a RuntimeException.

So, how can you create a function that will receive only an array whose elements implement Comparable and have all the same type (e.g. Integer, String, etc?)

Answer

Dirk picture Dirk · Jan 15, 2010

Use

static <T extends Comparable<? super T>> sort(T[] array);

which is the most general specification to accomplish the task. Basically, it asserts, that T is a type which can be compared to itself.