java - Why am I losing type information? -


i have found interesting happen maps, rawtypes , generics. following code:

static {           map map = new hashmap ();           set <map.entry> set = map.entryset ();           (map.entry entry : set) {} // fine            (map.entry entry : map.entryset()) {} // compilation error } 

i getting compilation error type incompatibility, namely: "object cannot cast entry".

ideone convenience

why iterator on entryset() losing type information if there's no variable storing again?

the rawtypes shouldn't affect type map.entry object. or mistaken?

your example makes have type information never had. have written:

map map = new hashmap (); set <map.entry> set = map.entryset(); (map.entry entry : set) {} // fine  (map.entry entry : map.entryset()) {} // compilation error 

but map.entryset() returning set, not set <map.entry>. you've performed unchecked assignment "adds" type information.

in second loop, don't know what's inside set, can't iterate on set <map.entry> without explicit cast.

for example, compare original example 1 don't "add" type information unchecked assignment.

map map = new hashmap(); set set = map.entryset(); (map.entry entry : set) { } // object cannot cast entry (map.entry entry : map.entryset()) { } // object cannot cast entry 

in case, both loops produce compilation error.

this behaviour documented in java language specification, section 4.8:

the type of constructor (§8.8), instance method (§8.8, §9.4), or non-static field (§8.3) m of raw type c not inherited superclasses or superinterfaces erasure of type in generic declaration corresponding c. type of static member of raw type c same type in generic declaration corresponding c.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -