I'm trying to increment of value in hashmap. I'm using Java 8 and Netbeans, so wrote this code:
Map<P, Integer>color_match_hash = new HashMap<P, Integer>();
for(int k=0; k<color_match_hash.size(); k++){
if(color_match_hash.get(k).equals(P_Color.get(i))){
color_match_hash.merge(color_match_hash.get(k), 1, Integer::sum);
}
}
P is an object with 5 Integers. It is a simple algorithm, in which I want to increment value of key (k) and I got "incompatible types: Integer cannot be converted to P". What I'm doing wrong? I must add that I tried a lot of ways to increment this and in every I had the same message. Most efficient way to increment a Map value in Java
You have created a HashMap
with key of type P
and value of type Integer
.
First of all, you are iterating the map like we do for a list or array.
Secondly, this is a wrong usage - color_match_hash.get(k)
. The get
method expects a value having a data type P
(the key).
You can read How to efficiently iterate over each entry in a Java Map? , to see different ways to iterate over a map.
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.