-1

I'm trying to solve https://leetcode.com/problems/top-k-frequent-elements/ and have decided to use a PriorityQueue to store values of Map.Entry<Integer, Integer>. I have the following code:

class Solution {
    public int[] topKFrequent(int[] nums, int k) {

        HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>();

        for (int num : nums) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }

        PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<Map.Entry<Integer, Integer>>(k, (Map.Entry e1, Map.Entry e2) -> {
            Integer e1Val = e1.getValue();
            Integer e2Val = e2.getValue();
            return e1Val - e2Val;
        });

        for (var entry : countMap.entrySet()) {
            pq.add(entry);
        }

        return null;
        
    }
}

I am trying to have a custom comparator in my PriorityQueue which uses the value of the Map.Entry<Integer, Integer> to do the sorting.

However, I get the following error:

Line 15: error: incompatible types: Object cannot be converted to Integer
            Integer e1Val = e1.getValue();
                                       ^
Line 16: error: incompatible types: Object cannot be converted to Integer
            Integer e2Val = e2.getValue();
                                       ^
2 errors

Why is it saying that my Map.Entry getValue() is an Object when it is actually an Integer?

FlameDra
  • 1,807
  • 7
  • 30
  • 47
  • `Map.Entry e1` is your problem — that's a raw type, which means all the generics get resolved to Object. (There's probably a duplicate somewhere on this site, but I don't have time to search for it right now. :) ) – yshavit Jun 05 '23 at 21:34

1 Answers1

1

You're using raw Map.Entry for e1 and e2. Change it like,

PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<Map.Entry<Integer, Integer>>(k,
        (Map.Entry<Integer, Integer> e1, Map.Entry<Integer, Integer> e2) -> {
            Integer e1Val = e1.getValue();
            Integer e2Val = e2.getValue();
            return e1Val - e2Val;
        });

Or just remove the type hint for e1 and e2.

PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<Map.Entry<Integer, Integer>>(k, (e1, e2) -> {
    Integer e1Val = e1.getValue();
    Integer e2Val = e2.getValue();
    return e1Val - e2Val;
});
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249