How does java generics syntax help avoid type casting? -


below code,

import java.util.list; import java.util.arraylist;   public class dummy {     public static void main(string[] args) {         list<string> lst = new  arraylist<string>();         lst.add("a string");         lst.add("another string");         string s = lst.get(0);     } //end main } 

when constructor new arraylist<string>(); invoked, array of type object created.

enter image description here ..

lst holds object[0] array.

enter image description here

so, if array of type object gets created constructor, how javac not see type casting issue in statement string s = lst.get(0);, despite generic syntax used while invoking constructor?

here non-generic code:

public class mylist {      list mydata = new arraylist();      public void add(object ob) {         mydata.add(ob);     }      public object getatindex(int ix) {         return mydata.get(ix);     } } 

this code allow store object of type mylist instances even if contract of mylist specifies objects must of same type. if use mylist instance store string instances, must manually cast them string when retrieve them.

string mystring = (string) mylist.get(1); 

the above mylist class not type safe. possible above assignment statement fail classcastexception if object other string instance stored mylist instance (which can happen @ run-time without complaint).

here generified mylist class:

public class mylist<t> {      list<t> mydata = new arraylist<>();      public void add(t ob) {         mydata.add(ob);     }      public t getatindex(int ix) {         return mydata.get(ix);     } } 

now, compiler guarantees t instances can added , retrieved mylist instances. because compiler guarantees t instances returned, can use syntax without manual casting:

string mystring = mylist.get(1); 

the generified mylist class type-safe. compiler won't allow store t instances mylist instances, guarantees no classcastexceptions occur @ run-time. if examine byte-code, you'll find compiler has placed cast automatically.

generics in java compile-time only phenomenon. in byte-code, references t in mylist class above replaced object. process referred "type erasure". important remember type safety in java provided compiler only. if program compiles without errors and without warnings, program, generics , all, type safe. compiled program, however, has retained no information generic parameters.


Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -