我的代码如下,并导致我出错:
error: bad operand types for binary operator '-'
。
我要减去Integer和int,但是我认为Java现在会自动为我们转换该值,它不会引起任何错误。如果尝试打印curr.getValue()的值,则会得到正确的Integer值。但是,当我尝试减去或比较它时,会出现错误。我是否需要将Integer转换为int,然后执行“ +”和“-”之类的操作?是否不应该将它们自动从Integer转换为int,反之亦然?
class Solution {
private String function(String s){
HashMap<Character, Integer> map = new HashMap<>();
for(char ch: s.toCharArray()){
Integer count = map.get(ch);
if(count == null){
count = 0;
}
map.put(ch, count += 1);
}
Queue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>(s.length(), (a, b) -> b.getValue() - a.getValue());
pq.addAll(map.entrySet());
Queue<Map.Entry<Character, Integer>> q = new LinkedList<>();
StringBuilder sb = new StringBuilder();
while(!pq.isEmpty()){
Map.Entry curr = pq.poll();
sb.append(curr.getKey());
curr.setValue( curr.getValue() - 1 ); //this causes an error.
q.offer(curr);
if(q.size() < 2){
continue;
}
Map.Entry e = q.poll();
if(e.getValue() > 0){
pq.offer(e);
}
}
return sb.toString().length() == s.length() ? sb.toString() : "";
}
public String reorganizeString(String S) {
return (function(S));
}
}
请告诉我是什么导致此错误?