处理 Java 泛型错误
我在以下代码中有一些泛型:
public <T extends Comparable<T>> int insertionSort(T[] a) {
// throw new RuntimeException("not implemented");
final int L = a.length;
int compares = 0;
for(int i = 1; i < L; i++){
for(int j = i; j > 0 && a[j].compareTo(a[j - 1]) < 0; j--){
Comparable tmp = a[j]; // PROBLEM HERE
a[j] = a[j - 1];
a[j - 1] = tmp; // PROBLEM HERE
compares++;
}
}
return compares;
}
// PROBLEM HERE
- 代码中的这两行有错误。
错误是我无法完成作业。
I have some generics in the following code:
public <T extends Comparable<T>> int insertionSort(T[] a) {
// throw new RuntimeException("not implemented");
final int L = a.length;
int compares = 0;
for(int i = 1; i < L; i++){
for(int j = i; j > 0 && a[j].compareTo(a[j - 1]) < 0; j--){
Comparable tmp = a[j]; // PROBLEM HERE
a[j] = a[j - 1];
a[j - 1] = tmp; // PROBLEM HERE
compares++;
}
}
return compares;
}
// PROBLEM HERE
- those two lines in the code have a fault.
The errors are I can't make the assignments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
a[j]
是T
,而不是Comparable
。您只能将其放入
T
类型的变量中。a[j]
is aT
, not aComparable
.You can only put it into a variable of type
T
.您的问题是
Comparable
是一个接口,而不是一个类。您需要创建一个实现Comparable
的类的对象。如果
T
实现Comparable
,那么您可以将 tmp 声明为T
并使用它:Your problem is that
Comparable
is an interface, not a class. you need to create an Object of a class that implementsComparable
.If
T
implementsComparable
, than you can declare tmp as aT
and use that:使用 T tmp 而不是 Comparable tmp,我认为这应该可以修复它。
instead of Comparable tmp, use T tmp and that should fix it I think.
代码中需要注意的事项:
正如编译器明确指出的那样,您的分配是错误的! :-)
Comparable tmp = a[j];
这会起作用,因为这是真实且正确的。由于 T 扩展了 Comparable,因此 T 是一个 Comparable。
这是行不通的,因为您试图将超类实例分配给子类实例。 Comparable 不保证具有 T 行为。因此出现了错误。
您可以尝试参数化该函数所在的类。使用该参数来定义 T。同样,您可能需要使用接口。除非我们更多地了解其他相关的设计目标,否则很难提供建议。就代码而言,该错误是正确且合理的。
Things to note down in your code:
Your assignment is wrong as clearly pointed out by the compiler! :-)
Comparable tmp = a[j];
this will work, because this is true and correct. Since T extends Comparable, T is-a Comparable.
This will not work, because you are trying to assign a superclass instance to a subclass instance. Comparable is not guaranteed to have T behavior. Hence the error.
You can try and parameterize your class in which this function lies. Use that parameter to define T. Again, You may need to work with interfaces. Unless we know more about the other related design goals, difficult to advice. Code wise, the error is correct and justified.