Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and sorting in Java

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?)

like image 922
peninha Avatar asked Jan 15 '10 13:01

peninha


People also ask

How do you write a generic sort in Java?

Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements.

What are generics in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

Is comparator a generic?

Java Comparator Example (Generic) This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic. In this class, we are printing the values of the object by sorting on the basis of name and age.

What is sorting in Java?

The sorting is a way to arrange elements of a list or array in a certain order. The order may be in ascending or descending order.


2 Answers

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.

like image 85
Dirk Avatar answered Sep 21 '22 19:09

Dirk


Dirk's answer is the best you can get, but Google Collections used exactly as you wrote to avoid bug in javac:

Why do you use the type <E extends Comparable> in various APIs, which is not "fully generified"? Shouldn't it be <E extends Comparable<?>>, <E extends Comparable<E>> or <E extends Comparable<? super E>>?

The last suggestion is the correct one, as explained in Effective Java. However, we will be using <E extends Comparable<E>> on parameterless methods in order to work around a hideous javac bug. This will cause you problems when you use a very unusual type like java.sql.Timestamp which is comparable to a supertype. (Needs more explanation.)

From: http://code.google.com/p/google-collections/wiki/Faq

Now it's up to you...

like image 31
nanda Avatar answered Sep 24 '22 19:09

nanda