[英]I have trouble incrementing a variable. Why?
這有什么問題嗎? 具體來說, intCount.put(i, intCount.get(i)++)
有什么問題?
public static Map<Integer, Integer> countNumbers(List<Integer> list) {
Map<Integer, Integer> intCount = new TreeMap<>();
for (Integer i : list) {
if (intCount.get(i) == null) {
intCount.put(i, 1);
} else {
intCount.put(i, ++intCount.get(i));
}
}
return intCount;
}
另一方面,這有效
public static Map<Integer, Integer> countNumbers(List<Integer> list) {
Map<Integer, Integer> intCount = new TreeMap<>();
for (Integer i : list) {
if (intCount.get(i) == null) {
intCount.put(i, 1);
} else {
intCount.put(i, intCount.get(i) + 1);
}
}
return intCount;
}
這是否意味着我不能遞增Integer
s,只能遞增int
原語? 問題是當我像這樣將Integer
轉換為其各自的原語(或者更確切地說,將Integer
返回方法轉換為其各自的原語)時
intCount.put(i, ++(int)(intCount.get(i)));
它也不起作用? 為什么?
Main.java:30:錯誤:意外類型
intCount.put(i, ++(int)(intCount.get(i)));
^ 必需:變量
發現:值
1 個錯誤
intCount.get(i)
獲取一個值,沒有要遞增的變量。 無論如何,我會完全刪除if
和else
並使用Map.getOrDefault(Object, V)
類的
intCount.put(i, intCount.getOrDefault(i, 0) + 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.