in java, what is wrong with this assignment:
Map<String, Object> mObj = new HashMap<String, String[]>();
I get:
error: incompatible types: HashMap<String,String[]> cannot be converted to Map<String,Object>
Since String[]
is an Object
, that should work.
If I cast to an unparameterized Map
like this: Map<String, Object> mObj = (Map) new HashMap<String, String[]>();
, it is working but of course, I get a warning and it is dirty.
Further more, I feel that my first assignment should work.
Thank you !
PS: I cannot simply change new HashMap<String, String[]>();
to new HashMap<String, Object>();
because in reality, I call a method that returns a Map<String, String[]>();
and of course, I cannot change this method. Thank you again.
The error is is because generics do not support subtyping. Number a = new Integer(5)
is valid case. But once you put generics it gives compilation error ArrayList<Number> a = new ArrayList<Integer>()
is not allowed. See if this link helps https://dzone.com/articles/5-things-you-should-know-about-java-generics to understand some guidelines on Generics.
Lets' see what could happen if what you wrote would be possible:
HashMap<String, String[]> foo = new HashMap<String, String[]>();
Map<String, Object> bar = foo;
bar.put("key",new Object());
String[] baz = foo.get("key"); // <-- ClassCastException
See the problem? A series of normal, mundane operations will cause ClassCastException
in a place where you would expect it wouldn't be possible to emit one.
Edit: To summarize, Map<String, Object>
is not a supertype of Map<String, String>
, Map<String, Object[]>
or Map<String, String[]>
, so the assignment will not work, as the types aren't compatible. This is where wildcards come in; see this answer and this one too
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With