1

I have a class which objects are constructed with a map of strings and maps of string and a generic type that extends Number, like this:

public MyClass(Map<String,HashMap<String,? extends Number>){ ... }

I also have another class that extends number:

public Class MySecondClass extends Number { ... }

In an external method i create a map made of string and maps of strings and MySecondClass objects

public void myMethod() {
    ...
    Map<String, HashMap<String, MySecondClass> foo = ...;
    ...
    }

And it looks like i could call the constructor of MyClass using the foo map without any problem, because MySecondClass extends Number, but i get keep getting and error that says:

MyClass(java.util.Map<java.lang.String, java.util.HashMap<java.lang.String, ? extends java.lang.Number>>) in MyClass cannot be applied
 to (java.util.Map<java.lang.String, java.util.HashMap<java.lang.String, MySecondClass>>)

  and i can't understand why.. i also have other methods which calls the same constructor using similar maps but instead of using MySecondClass they use Long or Integer that obviously extends Number and there should not be difference between those classes because they all extend Number.. what did i do wrong?

I am using java 10

Idan Str
  • 614
  • 1
  • 11
  • 33
  • It's a nested wildcard - they don't work like you think they work, you need `Map` – Boris the Spider May 16 '18 at 17:27
  • But actually i can call the costructor of that class using a `Map>` and it works, why ? – Valerio.pescatori May 16 '18 at 17:30
  • Random question - you have a `Map` as the outer but a specific implementation as the inner - why? Why not program to the interface? – Boris the Spider May 16 '18 at 17:32
  • 1
    That's interesting — I can't use a Map> any more than I can use MySecondClass in place of Long. Also, are we are the inner maps typed as HashMap or LinkedHashMap? These details could be important. – NickMarkham May 16 '18 at 17:33
  • Because i'm sure the inner map will be a HashMap or a LinkedHashMap, so why should i use Map as the inner? i use Map as the outer cause i call the constructor using `Map.of()` – Valerio.pescatori May 16 '18 at 17:35
  • Have a look at https://stackoverflow.com/questions/49792654/incompatible-types-when-using-upper-bounding-wildcard . I'd consider this as a duplicate (but am hesitant to use the dupehammer as long as you don't confirm that this answers your question) – Marco13 May 16 '18 at 17:38
  • yes, my bad i'm flagging it as a duplicate, thank you – Valerio.pescatori May 16 '18 at 17:52
  • Possible duplicate of [Incompatible types when using upper bounding wildcard](https://stackoverflow.com/questions/49792654/incompatible-types-when-using-upper-bounding-wildcard) – Valerio.pescatori May 16 '18 at 17:52
  • Another thought: for times when you want a Map of Maps, Guava's Table classes can come in very handy. – NickMarkham May 16 '18 at 18:03

0 Answers0