What's wrong with this? Specifically, what's wrong with 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;
}
This works, on the other hand
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;
}
Does it mean I can't increment Integer
s, only int
primitives? The problem is when I cast Integer
into its respective primitive (or rather, an Integer
returning method into its respective primitive) like this
intCount.put(i, ++(int)(intCount.get(i)));
it doesn't work either? Why?
Main.java:30: error: unexpected type
intCount.put(i, ++(int)(intCount.get(i)));
^ required: variable
found: value
1 error
intCount.get(i)
gets a value, there is no variable to increment. Regardless, I would remove the if
and else
entirely and use Map.getOrDefault(Object, V)
like
intCount.put(i, intCount.getOrDefault(i, 0) + 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.