有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    换线

    public class MinPriorityQueue<T extends Comparable<T>>
    

    为此:

    public class MinPriorityQueue<T extends Comparable<? super T>>
    

    这里的问题是方法Dijkstra中的T extends ShortestPathVertex<E>,因此T不需要直接实现Comparable。但这在你的MinPriorityQueue版本中是必要的。我的改变解决了这个问题

    说明:In MinPriorityQueue<T> Q = ...{}是ShortestPathVertex<E>的一个子类型,它实现了Comparable<ShortestPathVertex<E>>。这意味着TShortestPathVertex<E>类型的值(这是T的超类型)是可比的。但是在MinPriorityQueue的版本中,您定义T必须与同一类型T相比较。如果还希望接受超级类型,则必须通过<? super T>来定义它

    您可以尝试(只是为了演示):在方法Dijkstra中,用ShortestPathVertex<E>替换T的每次出现。这也适用于类MinPriorityQueue的更简单定义

    以这种方式使用super的另一个例子是:查看Java类库中的方法Collections.binarySearch