Generics
Generics were introduced in Java 1.5. Generics help the user to create the general purpose code that has abstract type in its definition. That abstract type can be replaced with any concrete type in the implementation.
For example, the list interface or its implementations, such as ArrayList
, LinkedList
and so on, are defined with generic type. Users can provide the concrete type such as Integer
, Long
, or String
while implementing the list:
List<Integer> list1 =new ArrayList<Integer>(); List<String> list2 =new ArrayList<String>();
Here, list1
is the list of integers and list2
is the list of strings. With Java 7, the compiler can infer the type. So the preceding code can also be written as follows:
List<Integer> list1 =new ArrayList<>(); List<String> list2 =new ArrayList<>();
Another huge benefit of generic type is that it brings compile-time safety. Let's create a list without the use of generics:
List list =new ArrayList<>();...