Here is the case, I have two classes A, B, and a generic interface C
Class A implements Comparable<A> {...}
interface C<T> {...}
//this class is not longer generic type, I do not know if this matter.
Class B extends A implements C<A> {...}
Then, at other class, I got a B List and sort it as follow
List<B> list = new ArrayList<B>();
Collections.sort(list);
This works perfectly, but now I would like to change the list of B to the generic interface C, so that it can be more general.
List<C<A>> list = new ArrayList<C<A>>();
Collections.sort(list);
This time I got the Error as follow:
Bound mismatch: The generic method
sort(List<T>)of typeCollectionsis not
applicable for the arguments(List<C<A>>). The inferred typeC<A>is not a
valid substitute for the bounded parameter<T extends Comparable<? super T>>
I have tried the following modifications (of course does not work):
- change
Ctointerface C<T> extends Comparable<T>{...} - change
Btoclass B extends A implements C<A>, Comparable<T> {...}
Can anybody help me?
As you would have already seen from the error messages, these two won’t work together as there will be a conflict in
B‘s definition w.r.t toComparable<A>andComparable<C<A>>.Since
Ais already implementingComparable<A>, you can achieve the followingby defining a
ComparatorforC<A>as follows:and then applying the sort method with this comparator: