java HashMap无法识别整数
我写了以下两种方法:
private Integer[] cutDownRecommendations(Shiur shiur, int numberOfRecs, int[] recommendationRaw)
{
Integer[] recommendation = new Integer[numberOfRecs];
ArrayList<String> speakers = shiur.getSpeakers();
//next count up all the scores
HashMap<Integer, Integer> findCount = new HashMap<>();
for(String speaker : speakers) {
ArrayList<Integer> relevantShiurim = speakerShiurMap.get(speaker);
for(int id : relevantShiurim) {
if(!findCount.containsKey(id)){
findCount.put(id,1);
}else{
int score = findCount.get(id);
findCount.put(id,++score);
}
}
}
recommendation = HashSetSortByValue.hashMapKeysSortByValue(findCount);
return recommendation;
}
在“HashSetSortByValue”类中,我有以下方法:
public static Comparable[] hashMapKeysSortByValue(HashMap<Comparable, Comparable> unsorted)
{
int len = unsorted.size();
Comparable[] orderedKeysByValue = new Comparable[len];
//convert keys into an array
Comparable[] keys = new Integer[len];
int position = 0;
for(Comparable item : unsorted.keySet()) keys[position++] = item;
Comparable[] values = new Integer[len];
position = 0;
for(Comparable item : unsorted.values()) values[position++] = item;
merge(values, keys);
//TODO fill this in
return orderedKeysByValue;
}
我收到以下行的编译器错误:
recommendation = HashSetSortByValue.hashMapKeysSortByValue(findCount);
return recommendation;
错误显示:
The method hashMapKeysSortByValue(HashMap<Comparable,Comparable>) in the type HashSetSortByValue is not applicable for the arguments (HashMap<Integer,Integer>)
根据java API,Integer类实现了Comparable,那么为什么我会得到这个错误呢
# 1 楼答案
您看到这个问题是因为Java泛型中称为“擦除”的概念。Java使用“擦除”来支持向后兼容性。i、 不使用泛型的Java代码
使用下面的方法签名应该不会产生编译时错误
public static <T extends Comparable> T[] hashMapKeysSortByValue(HashMap<T, T> unsorted)
这里,
T
是以Comparable
为边界的参数类型,这意味着允许Compariable的每个子类型作为类型参数