开发者

Why i can't put string into a field which is something that extends Object

开发者 https://www.devze.com 2023-03-25 08:45 出处:网络
I have a map like the one below final Map<String, ? extends Object> map Can anyone tell me why this operation is not possible..?

I have a map like the one below

final Map<String, ? extends Object> map

Can anyone tell me why this operation is not possible..?

开发者_开发百科
productMap.put("min", String.valueof(34));

What should be the turnaround...


You can't add any object to a Map because the compiler knows the value is some class which extends Object, but doesn't know which one.

Map<String, ? extends Object> map = new HashMap<String, Integer>();
Object val = map.get("min"); // this is ok.
map.put("min", Integer.toString(34)); // not allowed.

Instead you can use

Map<String, Object> map = new HashMap<String, Object>();
Object val = map.get("min"); // this is ok.
map.put("min", Integer.toString(34)); // is ok.


The wildcard provides flexibility (you can now assign a HashMap<String, String> or a HashMap<String, Integer> to map) in exchange for a condition: you cannot write to map, because it doesn't know what the actual class of the values will be.

See here for a good tutorial.


You've told the compiler that the map values will be some specific subtype of Object. ? could be anything -- you could do:

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

So String might be invalid.

You probably want the simpler Map which does allow any value.

Or you can "cheat" and do a cast which hides the generic type:

((Map)productMap).put("min", String.valueof(34));

But that trick is not best practice & to be used sparingly if at all.


By declaring the map as Map<String, ? extends Object>, you state that the second type is "anything which inherits from object". This is equivalent to declaring the map as Map<String, ?>. This declaration enables assignments like

final Map<String, ? extends Object> map = new HashMap<String, Integer>();

I think this example makes it clear why the compiler forbids inserting strings into the map: The value type is unspecified in the declaration.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号