2

I am trying to have a map containing multiple maps. Each of those submaps contain a Set of type Domain. However, I cannot give to the super-map maps containing domains with a specific Domain (e.g.: Domain).

Domain<Spell> spells = new Domain<>("spells");

Map<String, Domain> map = new TreeMap<>();
map.put(spells.getName(), spells);

Map<String, Domain<Spell>> library = new TreeMap<>();
library.put(spells.getName(), spells);

Map<String, Map<String, Domain>> mapLibrary = new TreeMap<>();
mapLibrary.put("test", library);

However I get the following error at the last line of code:

The method put(String, Map<String,Domain>) in the type Map<String,Map<String,Domain>> is not applicable for the arguments (String, Map<String,Domain<Spell>>)

How can I do it so that I could have a super-map containing maps with multiple different Domain with different generic parameters?

Additional info: there are four classes that extend Magic:

- Spell extends Magic<Spell>
- Prayer extends Magic<Prayer>
- Mental extends Magic<Mental>
- Elemental extends Magic<Elemental>

The superclass has a generic parameter since it contains the Domain of which it is part, and as of such must specify the correct type of Domain.

Edit about the duplicate: As said above and in the comments, I seek to find a workaround to the issue, not to know why. The answers to the other question simply tell why.

Barracuda
  • 332
  • 4
  • 17

1 Answers1

0

The answer is Map<String, Map<String, ? extends Domain<?>>> mapLibrary = new TreeMap<>()

The error message has told you that Map<String, Domain<Spell>> is not assignable to Map<String, Domain>. This is what @john16384 commented, List<Dog> is not List<Animal>. But List<Dog> is List<? extends Animal>. So your should declare your generic as Map<String, Map<String, ? extends Domain<?>>.

Dean Xu
  • 4,438
  • 1
  • 17
  • 44