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?)
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.
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.
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.
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.
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.
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 likejava.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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With