HashMap可比性无法识别整数

时间:2018-07-30 03:40:36

标签: java hashmap integer comparable

我编写了以下两种方法:

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 个答案:

答案 0 :(得分:0)

由于Java泛型中称为“擦除”的概念,您正在看到此问题。 Java使用“擦除”来支持向后兼容。即不使用泛型的Java代码。

使用下面的方法签名应该不会给您任何编译时错误

public static <T extends Comparable> T[] hashMapKeysSortByValue(HashMap<T, T> unsorted)

这里,T是受Comparable限制的参数类型,这意味着Comparable的每个子类型都可以用作类型参数。