Question

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.

Was it helpful?

Solution

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); 
}

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top