Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is not valid in this assignment: `Map<String, Object> mObj = new HashMap<String, String[]>();`?

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.

like image 474
ncenerar Avatar asked Dec 03 '22 15:12

ncenerar


2 Answers

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.

like image 156
Madhusudana Reddy Sunnapu Avatar answered Jan 18 '23 10:01

Madhusudana Reddy Sunnapu


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

like image 31
Tassos Bassoukos Avatar answered Jan 18 '23 10:01

Tassos Bassoukos