I get error on second line, isn't all items an Object?
Map<String, ?> value; // I get value from some place
Map<String, Object> val = value;
The ? in generics (in Java land) denotes that it can be substituted for any type (this type may be optionally bounded.) In the case of generics, Object cannot safely be substituted for any type this way (it runs into the problem of generics and subtyping, because generics are erased at runtime.)
Thus, the two are not semantically identical as you might first expect, hence the compilation error.
As an example of what could go wrong if this were allowed, you could do:
Map<String, ?> value = new HashMap<String, String>();
Map<String, Object> val = value; //This line would fail in real life, but assuming it passes...
val.put("Hello", 0); //We could do this!
...which clearly doesn't make any sense - the HashMap is of type <String, String> yet you've put an Integer in it!
This is where the ? representation differs - you could not put anything other than an Object in the map without causing a compile error:
value.put("Hello", 0); //Error
It's worth noting that arrays do not carry these same restrictions, since they are reified and thus can throw meaningful exceptions at runtime when a type mismatch occurs. (Whether this is preferable is a matter of debate, but personally I much prefer catching errors early at compile time!) Since generics can't do this, the compiler has to ensure their safety at compile time.
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