Java Generic Type Inference Strange Behavior? -


can explain behaviour me:

note: t never used in somethinggeneric

   public static class somethinggeneric<t> {         public list<string> getsomelist() {             return null;         }     }  final somethinggeneric<object> somethinggenericobject = new somethinggeneric<object>(); final somethinggeneric<?> somethinggenericwildcard    = new somethinggeneric<object>(); final somethinggeneric somethinggenericraw            = new somethinggeneric<object>();  (final string s : somethinggenericobject.getsomelist()) { }   // 1 - compiles (final string s : somethinggenericwildcard.getsomelist()) { } // 2 - compiles (final string s : somethinggenericraw.getsomelist()) { }      // 3 - not compile! 

(1) , (2) compiles (3) fails following message:

incompatible types found   : java.lang.object required: java.lang.string 

if wants full code, here is. have verified in both java 5 , 6.

well, interesting question despite downvotes. believe answer question lies in portion of jls:

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

effectively, method public list<string> getsomelist gets effective signature of public list getsomelist, in scenario accessing via raw type. , such, list iterator resulting list 'returns' objects instead of strings.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -