how the type information is retrieved in generics (Erasure) in Java? -
by using generics, detect possible during compilation. example,
list<string> list = new arraylist<string>(); //list.add(new integer(45)); cause compilation error. list.add("car"); list.add("bus"); list.add("bike"); string vehicle = list.get(0); //compiler-generated cast
when use raw type instead of generics before java 1.5, needs explicit casting. example,
list list2 = new arraylist(); list.add("car"); list.add("bus"); list.add("bike"); string vehicle = (string)list.get(0); //explicit casting necessary
however generics, type erasure occurs. type information lost in runtime. if, so, how jvm know object type retrieving during runtime, whether string object or person object (compiler generated cast above). valid generics, can cause runtime errors.
list<object> test = new arraylist<object>(); test.add("hello"); test.add(new integer(34));
finally, joshua bloch mentions on page 115 (item 23, effective java) set<object>
parameterized type representing set can contain objects of type, set<?>
wild card type representing set can contain objects of unknown type , set
raw type, opts out of generic type system.
i understand means above statement. clarifications help
the compiler inserts cast operations when retrieving items generic methods; way jvm knows treat result of list.get(0)
string
. why heap pollution (inserting wrong type of object generic collection) can result in classcastexception
@ runtime.
regarding wildcards:
set<object>
's generic typeobject
. can insert , retrieveobject
instances it, can't passset<integer>
method expectingset<object>
, since method might planning add non-integer
object set.set<?>
has unspecified generic type. method can retrieveobject
(sinceobject
) , can call universal methods onhashcode
ortostring
, can't add set.set
, mention, raw type , shouldn't used in new code.
Comments
Post a Comment