Sorting in a generic class
I am creating a generic class that has a method that is supposed to sort through an array collection that may either be a Book or it may be a CD. I implemented Comparable in the two type classes and am trying to sort the array in the GenericCollection class.
My method looks like this right now:
public void sort(){
for (int i = 0; i < collection.length; i++) {
for (int j = 0; j < collection.length; j++) {
if (((T)collection[i]).compareTo((T)collection[j]) > 0){
T t = (T)collection[i];
collection[i] = collection[j];
collection[j] = t;
}
}
}
}
This gives me the error that Object is not comparable. If I try to cast to type T then I get the error that T is undefined for CompareTo. If I try something like:
<T extends Comparable>
I can compile but I get a runtime error even though I have Comparable defined in both types that are using this class.
How do I get the Generic type to be ab开发者_高级运维le to run the compareTo methods in their own classes.
Thanks for any help.
You should be using a built-in sort, however to answer your question you need to have.
<T extends Comparable<T>>
or the more obscure
<T extends Comparable<? super T>>
See
public static <T extends Comparable<? super T>> void sort(List<T> list)
The moral of the story: If you are not going to use a built-in function which does exactly what you want, you should at least understand it first because it might have some tips for you. ;)
If you need to implement your own sort algorithm, try to declare the type parameter of your generic collection class as
<T extends Comparable<T>>
This means, your class would be declared like this:
class GenericCollection<T extends Comparable<T>> { ... }
And of course, your book or CD classes should implement this exact type:
class Book implements Comparable<Book> { ... }
class CD implements Comparable<CD> { ... }
If you use the parameter <T extends Comparable>
, you are using a raw type, and these are only for compatibility with old (pre-generics) code, should never be used in new code.
精彩评论