0

i have created a hashmap with Color Objects as keys. My source code looks like this:

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

Now i would like to check if there is already a Color Object as a key in the HashMap. So i tried this:

if (hm.get(colorObject) != null){

Unfortunately it returns false, although the Color is the same. I print the color in the console and it is always java.awt.Color[r=254,g=0,b=0]. I also tried the method containsKey from HashMap.

So what is wrong? How can i check if there is an Object in the hashmap?

NilsH
  • 13,705
  • 4
  • 41
  • 59
JavaForAndroid
  • 1,111
  • 2
  • 20
  • 42
  • 3
    It should work if the `Color` object properly implements `equals` and `hashCode` (which i assume it does, since it's aparently `java.awt.Color`). – NilsH May 12 '13 at 09:04
  • 1
    Its possible that you added null for this color in the map by mistake. – Ashwinee K Jha May 12 '13 at 09:11

2 Answers2

2

try if(hm.containsKey(colorObject))

kelunik
  • 6,750
  • 2
  • 41
  • 70
0

I tried this:

final Map<Color, Integer> colors = new HashMap<>();
colors.put(new Color(3030), 1);
System.out.println(colors.get(new Color(3030)));

and the output was 1, as expected. Therefore your problem is not as general as you have scoped it in your question.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436