Generics was introduced in Java 5.
- We can store any objects in ArrayList. So if you store 3 Employee objects and 1 Customer object in the same arraylist, you will not get a compile time error, but when you try to retreive the object from the arraylist, you will get runtime error.
- In order to avoid the RTE, you will need to check if object is instance of a particular class leading to lot of code.
- By Generics, you can avoid this, by say List <Employees>
- Another feature is using “?” you can say List <? extends someclass>
- Like saying ? extends subclass instead of List <Superclass>Code that uses generics has many benefits over non-generic code:
- Stronger type checks at compile time:
A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
- Elimination of casts: If you use generics, then explicit type casting is not required.
- Enabling programmers to implement generic algorithms:
By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.