【问题标题】:Can't resolve 'Type argument is not within bounds of type-variable' error无法解决“类型参数不在类型变量范围内”错误
【发布时间】: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 书中算法的实践,我试图保持与伪代码相似的命名:))

标签: java generics


【解决方案1】:

改变这一行

public class MinPriorityQueue<T extends Comparable<T>>

到这里:

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

这里的问题是T extends ShortestPathVertex&lt;E&gt;在方法Dijkstra中,所以T不需要直接实现Comparable。但这在您的MinPriorityQueue 版本中是必要的。我的更改解决了这个问题。

解释:In MinPriorityQueue&lt;T&gt; Q = ... TShortestPathVertex&lt;E&gt; 的子类型,它实现了Comparable&lt;ShortestPathVertex&lt;E&gt;&gt;。这意味着TShortestPathVertex&lt;E&gt; 类型的值相当(T 的超类型)。但是在您的MinPriorityQueue 版本中,您定义T 必须与相同类型的T 具有可比性。如果你也想接受超类型,你必须用&lt;? super T&gt;定义它。

您可以尝试(仅用于演示):在方法Dijkstra 中,将T 的每个出现替换为ShortestPathVertex&lt;E&gt;。这也适用于类MinPriorityQueue 的更简单定义。

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

【讨论】:

  • 感谢您的解决方案完美运行。您能否详细说明so T needs not implement Comparable directly?我不明白ShortestPathVertex 已经宣布要执行 Comparable 怎么会不执行。
猜你喜欢
  • 2014-05-04
  • 2021-07-17
  • 2012-04-15
  • 2015-06-24
  • 2018-01-17
  • 2015-02-06
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多