0

I wrote the following two methods:

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;
}

In the "HashSetSortByValue" class I have the following method:

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;
}

I'm getting compiler errors for the following line:

recommendation = HashSetSortByValue.hashMapKeysSortByValue(findCount);
    return recommendation;

The error says:

The method hashMapKeysSortByValue(HashMap<Comparable,Comparable>) in the type HashSetSortByValue is not applicable for the arguments (HashMap<Integer,Integer>)

According to the java API the Integer class implements Comparable, so why am I getting this error?

Moish
  • 452
  • 1
  • 3
  • 13

1 Answers1

0

You are seeing this problem because of the concept called "Erasure" in Java Generics. Java uses "erasure" to support backward compatibility. i.e Java code which did not use generics.

Using below method signature should give you no compile time error

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

Here, T is a parameter type that is bounded by Comparable, meaning each subtype of Comparable is allowed as a type parameter.

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41