gpt4 book ai didi

java - 无法解决 'Type argument is not within bounds of type-variable' 错误

转载 作者:行者123 更新时间:2023-11-30 10:00:15 29 4
gpt4 key购买 nike

我有一个通用类 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。

最佳答案

改变这一行

public class MinPriorityQueue<T extends Comparable<T>>

为此:

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

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

解释:In MinPriorityQueue<T> Q = ... TShortestPathVertex<E> 的子类型实现Comparable<ShortestPathVertex<E>> .这意味着 TShortestPathVertex<E> 类型的值相当(这是 T 的父类(super class)型)。但是在你的 MinPriorityQueue 版本中你定义 T必须与同类型相当T .如果你也想接受父类(super class)型,你必须通过 <? super T> 来定义它.

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

另一个使用 super 的例子这样:看方法Collections.binarySearch在 Java 类库中。

关于java - 无法解决 'Type argument is not within bounds of type-variable' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58144657/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com