我有一個通用類ShortestPathVertex,它實現Comparable:public class ShortestPathVertex<E extends Number> implements VertexInterface, Comparable<ShortestPathVertex<E>>另一個MinPriorityQueue需要Comparable類型參數的泛型類: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 MinPriorityQueueShortestPath.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。
1 回答

慕的地10843
TA貢獻1785條經驗 獲得超8個贊
改變這一行
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 = ...
T
類型。這意味著與 type 的值(它是 的超類型)相當。但在您的版本中,您定義它必須與同一類型相當。如果您還想接受超類型,則必須通過 定義它。ShortestPathVertex<E>
Comparable<ShortestPathVertex<E>>
T
ShortestPathVertex<E>
T
MinPriorityQueue
T
T
<? super T>
您可以嘗試(僅用于演示):在方法中Dijkstra
替換每次出現的T
by ShortestPathVertex<E>
。這也適用于更簡單的 class 定義MinPriorityQueue
。
這種方式使用的另一個例子super
:查看Collections.binarySearch
Java類庫中的方法。
添加回答
舉報
0/150
提交
取消