views:

86

answers:

2

Hi there,

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.

A: 

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); 
}
Rahul
Ah I was type casting it with the (Integer) in front but I wasn't using the intValue() method. Ach. Thanks!
David
Be careful casting the untyped object, as you may generate a ClassCastException. If that's an acceptable risk, this will work fine.
jheddings
+2  A: 

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)

jheddings
It has to be Integer. You cannot use primitive types in generics.
Thanks... I was typing faster than my brain was compiling.
jheddings