我编写了一个通用方法来对 T 类型的对象进行排序。 我的编译器说“找不到符号:方法 lte(T)。
知道我的问题到底是什么吗?
interface Comparable<T>{
boolean lte(T t);
}
class Sort<T extends Comparable<T>> {
static <T> void sort(T[] s) {
for (int i = 0; i<s.length; i++) {
for (int j = i+1; j < s.length; j++) {
if (s[i].lte(s[j])) {
T t;
t = s[i];
s[i] = s[j];
s[j] = t;
}
}
}
}
public static void main(String[] args) {
String[] names = {"Pete","Jill","May","Anne","Tim"};
sort(names);
for (String s:names)
System.out.println(s);
}
}
最佳答案
您已经创建了 sort
通用方法,带有另一个 <T>
声明,但它不是 Comparable
。您的sort
方法是static
,所以它不能使用类的 <T>
。事实上,类的<T>
没有被使用。试试这个:
// Not generic here anymore
class Sort {
// Bound goes here
static <T extends Comparable<T>> void sort(T[] s) {
此外,String
不会扩展您的Comparable
接口(interface),所以这不起作用( String
甚至没有 lte
方法,无论如何)。您将需要传入一些实现您的的对象 Comparable
.
充其量,将您的界面命名为与内置(且众所周知)界面相同的名称会令人困惑。我建议重命名您的 Comparable
类似于 Lteable
的接口(interface).
关于java - 通用方法无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821683/