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 able to run the compareTo methods in their own classes.
Thanks for any help.
If you need to implement your own sort algorithm, try to declare the type parameter of your generic collection class as
This means, your class would be declared like this:
And of course, your book or CD classes should implement this exact type:
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.