英文:
Java Map.Entry getValue() is returning an Object even though it should be an Integer
问题
错误信息表明,在你的代码中,编译器无法确定 Map.Entry
的 getValue()
方法返回的对象类型是 Integer
。为了解决这个问题,你可以在 PriorityQueue
的构造函数中指定比较器的类型,这样编译器就能正确地识别 Map.Entry
中值的类型。以下是修复后的代码片段:
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(k, (Map.Entry<Integer, Integer> e1, Map.Entry<Integer, Integer> e2) -> {
Integer e1Val = e1.getValue();
Integer e2Val = e2.getValue();
return e1Val - e2Val;
});
通过在 PriorityQueue
构造函数中明确指定泛型参数类型,你可以解决类型不兼容的问题,确保编译器正确识别 Map.Entry
中值的类型为 Integer
。
英文:
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?
答案1
得分: 1
你使用原始的 Map.Entry
来定义 e1
和 e2
。将其更改为:
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;
});
或者只是移除 e1
和 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;
});
英文:
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;
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论