Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Map<String, ? extends Object> to Map<String, Object>

In Java 8, I am trying to cast Map<String, ? extends Object> to Map<String, Object>. I though that it would be safe given the constraint I put on the input Type (all ? must implement Object), but I get an unchecked cast warning.

Any idea where I reason wrong ? Any clean solution ? Thanks for your help !

like image 366
Antonin Avatar asked Apr 04 '18 16:04

Antonin


1 Answers

This cast is not safe. In particular:

Map<String, ? extends Object> before;
before.put("foo", "example"); // <-- illegal

Map<String, Object> after;
after.put("foo", "example"); // <-- legal

Observe that String is not a subclass of ? extends Object because you don't know ? but it is a subclass of the more general Object thus the second call is okay.

like image 197
WorldSEnder Avatar answered Sep 17 '22 17:09

WorldSEnder