java无法解析“类型参数不在typevariable的范围内”错误
我有一个泛型类ShortestPathVertex
,它实现了Comparable
:
public class ShortestPathVertex<E extends Number> implements VertexInterface, Comparable<ShortestPathVertex<E>>
以及另一个需要Comparable
类型参数的泛型类MinPriorityQueue
:
public class MinPriorityQueue<T extends Comparable<T>>
我需要创建一个MinPriorityQueue
实例,其中ShortestPathVertex
作为类型参数:
public static <E extends Number, T extends ShortestPathVertex<E>> void Dijkstra(WeightedDirectedGraph<T, E> G, int s) {
MinPriorityQueue<T> Q = new MinPriorityQueue<>(G.getVertices(), G.V()); // error
}
编译时会抛出错误:
ShortestPath.java:60: error: type argument T#1 is not within bounds of type-variable T#2
MinPriorityQueue<T> Q = new MinPriorityQueue<>(G.getVertices(), G.V());
^
where T#1,E,T#2 are type-variables:
T#1 extends ShortestPathVertex<E> declared in method <E,T#1>Dijkstra(WeightedDirectedGraph<T#1,E>,int)
E extends Number declared in method <E,T#1>Dijkstra(WeightedDirectedGraph<T#1,E>,int)
T#2 extends Comparable<T#2> declared in class MinPriorityQueue
ShortestPath.java:60: error: cannot infer type arguments for MinPriorityQueue<>
MinPriorityQueue<T> Q = new MinPriorityQueue<>(G.getVertices(), G.V());
^
2 errors
考虑到ShortestPathVertex
实现了Comparable
,我不明白它在抱怨什么。为什么它说ShortestPathVertex
不在Comparable
的范围内?我该如何解决它。我正在使用Java7.0
# 1 楼答案
换线
为此:
这里的问题是方法
Dijkstra
中的T extends ShortestPathVertex<E>
,因此T
不需要直接实现Comparable
。但这在你的MinPriorityQueue
版本中是必要的。我的改变解决了这个问题说明:}是
In MinPriorityQueue<T> Q = ...
{ShortestPathVertex<E>
的一个子类型,它实现了Comparable<ShortestPathVertex<E>>
。这意味着T
与ShortestPathVertex<E>
类型的值(这是T
的超类型)是可比的。但是在MinPriorityQueue
的版本中,您定义T
必须与同一类型T
相比较。如果还希望接受超级类型,则必须通过<? super T>
来定义它您可以尝试(只是为了演示):在方法
Dijkstra
中,用ShortestPathVertex<E>
替换T
的每次出现。这也适用于类MinPriorityQueue
的更简单定义以这种方式使用
super
的另一个例子是:查看Java类库中的方法Collections.binarySearch