Quick Points :
- The purpose of Generic is to
- provide type-safety (At compile time determined)
- Type casting issue – (If non generic is used TypeCasting is mandatory)
- A generic code can be written for different types like Sorting and Search for CustomeObjects
- Generics concept only applicable at Compile time, at Runtime no Generic is present
Why Generics ?
- Arrays are type safe when we put some value other than defined one it gives compile time error
- But in Collection like ArrayList the data type is not defined any type of object can be stored which causes the runtime exception when understermined type of object is tried to cast into another object
- Generics was introduced in java 1.5
- Generics enable classes and interfaces to be parameters while defining it, these parameters are type parameters.
- Type parameters helps to provide a way to reuse the same code but with different input argument types.
- The reason why Generics came into picture is to reduce the runtime exceptions in java programs, since before java 1.4 collections does not use to take parameters and developers where not sure which type of object is stored in that collection, developer always had take the object from the collection and cast it and check it, and if the object does not cast properly then it would result into a run time exception. To prevent it from happening using generics we can define what kind of object is stored in the collection while declaring it itself and could prevent the effort of casting the object and possible run time exception while code execution.
- Thus by using generics we could prevent a lot of run time exceptions by declaring the type along with collection declaration.
- We need not worry about casting the object since JVM already knows what kind of object is stored in the collection.
- We can implement sorting searching algorithm in a very generic way using the generics functionality.
Advantages of Generics over non generic code:
- Stronger type check at compile time
If violated then it results into a compile time error. - We can eliminate casting
List nameList = new ArrayList();
String name = (String)nameList.get(0);
List<String> nameList = new ArrayList<>();
String name = nameList.get(0); - Generic algorithms can be implemented to reuse search and sorting algorithms with the same code.