Why does a Java generic raw class erase all generics to object when type parameters are unspecified? -
this question has answer here:
- combining raw types , generic methods 5 answers
- why won't generic java code compile? 4 answers
if have class:
public class genericclass<tblah extends number> { public list<string> getlist() { return null; } } when attempt use method class:
public class otherclass { public void test() { genericclass = null; (string s : a.getlist()) { } } } why a.getlist() return list<object> until change line above loop to:
genericclass<number> = null; at point a.getlist() returns list<string> should do?
edit: don't understand why contract specified getlist() should affected whatsoever how declare variable 'a'. getlist() returns list<string>, doesn't matter tblah is.
because how generics work. not forget before generics when declared list list of object. expected put/get object , forced cast object correct type. still is list of object in runtime.
generics way compiler guarentee type safety at compile time assuming have no warnings. in runtime there no list<string>. there list. compiler puts automatic cast you, able in code write string s = list.get(i) without casting.
when declare genericclass a declaring raw type (you should warning on this) compiler not have way know type a.getlist() supposed return. uses object. when declare genericclass<number> = null; compiler knows type expect a.getlist() , uses desired one.
edit: should clarified compiler can know expect if respect contract of signature (i.e. case genericclass<number>). if don't respect contract (i.e. using raw type not extends number) contract not apply anymore. compiler behaves if no type information present. not forget compiler needs maintain backwards compatibility code created in pre-generics era
Comments
Post a Comment