Why cannot I write "Map<String,String> m = (Map<>)obj"?

Rémi Forax forax at univ-mlv.fr
Wed Jul 25 02:50:10 PDT 2012


On 07/25/2012 11:11 AM, Weijun Wang wrote:
> Just curious, if obj is of type Object, and I want to cast it to 
> Map<String,String>, why cannot I use the diamond operator?

Just because the grammar doesn't accept this case, the diamond operator 
<> as currently defined only works with new.

Cast like this are seen as ugly code, even if practically you sometimes 
have to use them due to legacy code,
because obj should have have been correctly typed by making the object 
that store it generics.
By example, instead of
    ArrayList list = ...
    Object obj = list.get(0);
    Map<String,String> map = (Map<String,String>)obj;

the code should be
    ArrayList<Map<String,String>> list = ...
    Map<String,String> map = list.get(0);

said differently, the whole thing of introducing generics is to avoid 
this kind of cast.

>
> Thanks
> Max

cheers,
Rémi




More information about the compiler-dev mailing list