How Generics works?
To understand how generics work, lets take a look at how things used to work before introduction of generics.
Lets take example of ArrayList. Prior to Generics, we used to declare ArrayList as follows :
and use it like :
i.e. The add() method used to accept Object references so it is not type-safe and the get() method used to return Object reference which we used to type-cast.
With the introduction of Generics, a new definition of ArrayList class looks like :
You can check the code for ArrayList in jdk here or any other standard implementations.
Whenever we use Generics, at the compilation time, the type parameter is replaced by the reference type that we use.
E.g. ArrayList<T> becomes ArrayList<Employee>
add(T t) becomes add(Employee t)
T get(int index) becomes Employee get(int index)
Lets take example of ArrayList. Prior to Generics, we used to declare ArrayList as follows :
ArrayList objList = new ArrayList();
and use it like :
objList.add(new Employee(1, "Sandeep", "IT"); objList.add("Sandeep") objList.get(0) //objList.get(index)
i.e. The add() method used to accept Object references so it is not type-safe and the get() method used to return Object reference which we used to type-cast.
With the introduction of Generics, a new definition of ArrayList class looks like :
class ArrayList<T> { ... add(T t) T get(int index) ... }
You can check the code for ArrayList in jdk here or any other standard implementations.
Whenever we use Generics, at the compilation time, the type parameter is replaced by the reference type that we use.
E.g. ArrayList<T> becomes ArrayList<Employee>
add(T t) becomes add(Employee t)
T get(int index) becomes Employee get(int index)
Comments
Post a Comment