I am trying to implement generics in Java using Comparable<T>
interface.
public static <T> T[] sort(T[] a) {
//need to compare 2 elements of a
}
Let's say, I want to override the compareTo
method for the above type T
in the Comparable
interface. Ie I need to compare two elements of my type T
, how will I do it? I don't know what my T
type will be.
You need to set a type constraint on your method.
public static <T extends Comparable<? super T>> T[] sort (T[] a)
{
//need to compare 2 elements of a
}
This forces the type T
to have the compareTo(T other)
method. This means you can do the following in your method:
if (a[i].compareTo(a[j]) > 0) }
}
Old question but...
As jjnguy responded, you need to use:
public static <T extends Comparable<? super T>> T[] sort(T[] a) {
...
}
Consider the following:
public class A implements Comparable<A> {}
public class B extends A {}
The class B
implicitly implements Comparable<A>
, not Comparable<B>
, hence your sort method could not be used on an array of B
's if used Comparable<T>
instead of Comparable<? super T>
Comparable<? super T>
. To be more explicit:
public static <T extends Comparable<T>> T[] brokenSort(T[] a) {
...
}
would work just fine in the following case:
A[] data = new A[3];
...
data = brokenSort(A);
because in this case the type parameter T
would be bound to A
. The following would produce a compiler error:
B[] data = new B[3];
...
data = brokenSort(B);
because T
cannot be bound to B
since B
does not implement Comparable<B>
.
尝试使用<T extends Comparable<T>>
然后compareTo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.