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 type object. can insert , retrieve object instances it, can't pass set<integer> method expecting set<object>, since method might planning add non-integer object set.
  • set<?> has unspecified generic type. method can retrieve object (since object) , can call universal methods on hashcode or tostring, can't add set.
  • set, mention, raw type , shouldn't used in new code.

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -