简体   繁体   English

在Comparable中使用泛型

[英]Using generics in Comparable

I am trying to implement generics in Java using Comparable<T> interface. 我正在尝试使用Comparable<T>接口在Java中实现泛型。

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. 假设我想在Comparable接口中覆盖上述类型TcompareTo方法。 Ie I need to compare two elements of my type T , how will I do it? 即我需要比较我的T型的两个元素,我将如何做? I don't know what my T type will be. 我不知道我的T型会是什么。

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. 这会强制类型T具有compareTo(T other)方法。 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: 正如jjnguy回应,你需要使用:

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> B类隐式实现了Comparable<A> ,而不是Comparable<B> ,因此如果使用Comparable<T>而不是Comparable<? super T>那么你的sort方法不能用在B的数组上Comparable<? super T> 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 . 因为在这种情况下,类型参数T将绑定到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不能绑定到B因为B没有实现Comparable<B>

尝试使用<T extends Comparable<T>>然后compareTo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM