【发布时间】:2019-09-28 08:32:17
【问题描述】:
我有一个通用类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 的范围内,我该如何解决。我正在使用 Java 7.0。
【问题讨论】:
-
您尝试过更新的 Java 编译器吗? Java 7 在这一点上绝对过时了。
-
我在这里找不到错误,所以除非这是旧编译器的问题(已知 9 之前的 Java 在泛型推理中有一些相当愚蠢的陷阱),否则我很难过。
-
@chrylis 我正在使用一台旧笔记本电脑,上面安装了 Java 版本 7,没有尝试更新版本。不过,我宁愿有一个适用于所有 java 版本的代码。
-
那么如果你在调用
Dijkstra的地方使用类型见证会发生什么? (注意,顺便说一句,你没有遵循 Java 代码关于变量和成员命名的约定。) -
@chrylis 抱歉,我不知道“类型见证”是什么,我在泛型方面没有那么先进。 (我应该遵循代码格式指南,但这段代码只是 CLRS 书中算法的实践,我试图保持与伪代码相似的命名:))