[英]Inferring a generic type from a generic type in Java (compile time error)
我有一個靜態函數,其泛型類型T
具有以下簽名
public static<T> List<T> sortMap(Map<T, Comparable> map)
應返回帶有某些屬性的地圖鍵列表。
現在我想傳遞S
類型的通用HashMap
Map<S,Double> map
調用泛型類中的靜態函數,該類將映射作為成員變量。
我在下面列出了一個最小的代碼示例。
但是,我收到一條錯誤消息( S
和T
都是T,但在我的代碼的不同范圍內,即T#1
= T
, T#2
= S
):
required: Map<T#1,Comparable>
found: Map<T#2,Double>
reason: cannot infer type-variable(s) T#1
(argument mismatch; Map<T#2,Double> cannot be converted to Map<T#1,Comparable>)
怎么解決這個問題? 我很驚訝Java不允許從泛型類型推斷泛型類型。 Java中的哪種結構可以用來處理那種更抽象的代碼推理?
代碼 :
public class ExampleClass<T> {
Map<T, Double> map;
public ExampleClass () {
this.map = new HashMap();
}
//the following line produces the mentioned error
List<T> sortedMapKeys = UtilityMethods.sortMap(map);
}
public class UtilityMethods {
public static<T> List<T> sortMap(Map<T, Comparable> map) {
// sort the map in some way and return the list
}
}
這不是T
和S
的問題,而是Comparable
和Double
。
出錯的原因是Map<T, Double>
不是Map<T, Comparable>
。
你必須擴大第二個類型參數的范圍。 就像是:
public static <T, S extends Comparable<S>> List<T> function(Map<T, S> map) {
//implementation
}
然后,您將能夠使用以下方法調用該方法:
Map<S, Double> map = new HashMap<S, Double>();
function(map);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.