1

I have a class B and C which both extends class A:

public class B extends A {...}
public class C extends A {...}

How can I use Java generics with a HashMap this way?

B b = new B();
C c = new C();

Map<String, ? extends A> map = new HashMap<String, A>();

map.put("B", b);
map.put("C", c);

Eclipse always shows an error:

The method put(String, capture#1-of ? extends A) in the type Map is not applicable for the arguments (String, B)

and

The method put(String, capture#1-of ? extends A) in the type Map is not applicable for the arguments (String, C)

Trein
  • 3,658
  • 27
  • 36
du-it
  • 2,561
  • 8
  • 42
  • 80

1 Answers1

6

Just change the type of the HashMap to <String, A>

Map<String, A> map = new HashMap<String, A>();
Trein
  • 3,658
  • 27
  • 36
  • Well, I did that... but what are then wildcards for? List appleList = new ArrayList(); List extends Fruit> list = appleList; ? – du-it Oct 09 '13 at 16:05
  • 1
    Please, refer to the official doc: http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html. It has an interesting explanation about wildcards. There is also a explanation on http://stackoverflow.com/questions/252055/java-generics-wildcards (see all the answers). Well, if the answer was helpful and solved your problem, don't forget to check it as accepted. – Trein Oct 09 '13 at 16:15