2

I have the following classes:

abstract class A
{
    protected HashMap<Integer, ?> genericMap;

    public HashMap<Integer,?> getMap(){ 
        return this.genericMap;
    }

}


class B extends A
{
    public B() { 
        this.genericMap = new HashMap<Integer,Rock>();
    }

    public Rock getRock(Integer key){ 
        return (Rock) this.genericMap.get(key);
    }

    public void addRock(Integer key, Rock value){
        this.genericMap.put(key, value); 
    }

}

Basically all the classes that extends A (like B, C, D, etc...) are going to instantiate in the constructor an HashMap with the same key type but a different type for the value.

When I do the get of the hashmap value, in a subclass, I simply need to do the cast.

But when I try, in a subclass, to put something into the hashmap I get the following error:

The method put(Integer, capture#3-of ?) in the type HashMap<Integer, capture#3-of ?> is not applicable for the arguments (Integer, Rock).

I've also tried the arguments (Integer, Object), but same error.

What I'm doing wrong? Thank you.

JohnLocke
  • 23
  • 5
  • You've defined your `HashMap` as `new HashMap();` and you're trying to add a `Integer, Object` entry in it. – Titus May 07 '17 at 16:36
  • @Titus Like I said, I've also tried to add an "Integer, Rock" entry but same problem. – JohnLocke May 07 '17 at 16:38
  • Why not just replace `?` with '`Object` in your HashMap declarations? – Chris May 07 '17 at 16:39
  • @Chris because then I couldn't define the HashMap as new HashMap(); – JohnLocke May 07 '17 at 16:40
  • @JohnLocke Good point I missed that – Chris May 07 '17 at 16:47
  • Kind of a rough hack, but it appeas you will know you want a `HashMap` so why not just cast before calling `put()`? `((HashMap) this.genericMap).put(key, (Rock) value);` should work but obviously this isn't very safe if `value` won't always be a subclass of `Rock` – Chris May 07 '17 at 16:51

0 Answers0