开发者

HashMap and incrementing values in Processing

I have a HashMap that I'm using in Processing and I'd like to increment the value in the map. I Google'd it and it showed me that the following code is correct:

if (colors.containsKey(ckey))
{
    colors.put(ckey, colors.get(ckey) + 1);
} else {
    colors.put(ckey, 1);
}

I keep getting:

The operator + is undefined for the argument type(s) Object, int

I'm not a Java coder but the reference says it returns an Object...do I have to use a .getValue() method on it to extract the int?

Maybe I'开发者_开发知识库m doing something else wrong? Hmmm.

Regards.


By default, the HashMap will let you store any kind of object without checking the type of object being used for either keys or values.

You should try to declare your HashMap using the type-safe declaration of your map:

HashMap<Color, Integer> colors = new HashMap<Color, Integer>();

(note that I'm assuming the keys for the map are java.awt.Color and values are always int)


I don't know anything about 'Processing' but looking at the above code, you need to typecast the value into an integer before adding.

Not sure what version of Java is being used here but you can do something like this.

if (colors.containsKey(ckey)) 
{ 

  int val = ((Integer) colors.get(ckey)).intValue();
  colors.put(ckey, new Integer(val + 1);
}
else 
{ 
  colors.put(ckey, 1); 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜