推断类型不是Comparablegenerics类型的有效替代
考虑一下代码:
public abstract class Item implements Comparable { protected T item; public int compareTo(T o) { return 0; // this doesn't matter for the time being } } public class MyItem extends Item { T object; } public class Foo { protected ArrayList list; } public class Bar extends Foo<MyItem> { public void sort() { Collections.sort(list); } }
排序调用给出错误:
绑定不匹配:类型集合的generics方法sort(List )不适用于参数(ArrayList <MyItem >)。 推断类型MyItem 不是有界参数的有效替代<T extends Comparable >
为什么这是错的?
如果MyItem
实现Comparable
为什么它不能替代?
对不起,如果有人问过,但我觉得这个问题有点具体。
实际上对这个错误的更详细的解释给你的javac
本身:
java:没有为
sort(java.util.ArrayList
找到合适的方法> sort(java.util.ArrayList
)> 方法
java.util.Collections.
不适用(无法从参数实例化,因为实际和forms参数列表的长度不同)sort(java.util.List ,java.util.Comparator super T>) 方法
java.util.Collections.
不适用(推断类型不符合推断的声明边界:sort(java.util.List ) MyItem
bound(s):java.lang.Comparable super MyItem
)>
所以,主要的问题是:
为什么方法Collections.
)不适用?
答案是 :
因为在Collections.
方法声明中有参数T
界限:
。
换句话说, T
必须在其上实现Comparable
接口。 例如, String
类实现了这样的接口: ...implements ... Comparable
。
在你的情况下, Item
类没有实现这样的接口:
Item
与Item
。
因此,要解决此问题,您应该将Item
类更改为:
public abstract class Item implements Comparable> { protected T item; public int compareTo(Item o) { return 0; // this doesn't matter for the time being } }
对于类型X
对象彼此可比较,类X
必须实现完全Comparable
。
这不是你的代码正在做的事情,你有一个Item
类,你正在实现Comparable
而不是Comparable
。 这意味着Item
可以与T
进行比较,但不能与Item
,这是必需的。
将Item
类更改为:
public abstract class Item implements Comparable> { protected T item; @Override public int compareTo(Item o) { return 0; // this doesn't matter for the time being } }
只需更改类如下:
public class MyItem extends Item implement Comparable> { T object; }
要么
public abstract class Item implements Comparable> { protected T item; public int compareTo(MyItem o) { return 0; // this doesn't matter for the time being }
}
错误提示向我们展示了。希望它有用。
您不需要将MyItem
类生成为只是为了查看效果。 以下课程足以看出会发生什么:
public class MyItem extends Item {}
现在您有以下电话:
Collections.sort(list);
正如morgano所说,sort方法将采用一个类型为T的集合,该类型T必须与T相当。您的MyItem
类正在扩展Item
,这导致MyItem
与String
s相当。
通过一个类实现Comparable
接口的小开关,您将获得预期的结果:
public abstract class Item { protected T item; } public class MyItem extends Item implements Comparable { @Override public int compareTo(MyItem o) { return item.compareTo(o.item); // just an example } }
现在,对Collections.sort(list)
的调用将起作用。