Generics is a way of implementing generic programming. Generic programming provides the facility like for a set of related methods, declare a single method that support any valid types. Generics are introduced in java 5. In java, generics are added because of Compile time type safety.
Let us understand with an example. We have an ArrayList of string type and add an integer type element. Before java 5 this code will compile and throw exception at the runtime which is worse. Generics provides the facility of compile time type safety i.e. compiler check that the correct types should be used at the correct places and no ClassCastException.
How generics work?
Generics work on the concept of “Type Erasure”. As we discussed above generics are used for compile time type safety i.e. they work at the compile time. At the compile time java compiler uses the Type Erasure feature to erase or remove the generics type code and convert the code without generics.
Main features of generics:
- 1. Compile time type safety.
- 2. Removing risk of ClassCastException at run time.
- 3. No casting.