java - Why this piece of code isn't compilable -
here small piece of code , don't understand why javac can't compile it. miss? there errors?
public class helloworld<t> { private static enum type { } private t value; private list<type> types = new arraylist<>(); public t getvalue() { return value; } public list<type> gettypes() { return types; } public static void main( string[] args ) { ( type type : new helloworld().gettypes() ) { // error: type mismatch: cannot convert element type object helloworld.type } } }
why gettypes()
returning object
(raw) list when should type
list?
this looks compiler limitation me. gettypes
returns list<type>
, using raw helloworld
type should make no difference.
that said, either of these 2 solutions overcome error :
create parameterized type of
helloworld
instead of raw type :for (type type : new helloworld<integer>().gettypes() ) { // type do, chose // integer arbitrarily show // doesn't matter }
use local variable store list before using :
list<type> types = new helloworld().gettypes(); (type type : types) { }
anyway, parameterized types should preferred on raw types, i'll use first solution (with whatever type parameter makes sense in class).
Comments
Post a Comment