Java Generics was added in Java 5 to provide compile time type checking and removing risk of ClassCastException which was common while working with collection classes.
123
// Before Java 5Listlist=newArrayList();
123
// Java 5 and afterList<String>list=newArrayList<String>();
We can define our own classes with generic type. A generic type is a class or interface that is parameterized over types. We use bracket (<>) to specify the type parameter.
Then we can create this class with setting any parameter type that we want as below:
JavaGeneric.java
1 2 3 4 5 6 7 8 9101112131415
packagecom.java.core.generic;publicclassJavaGeneric{publicstaticvoidmain(String[]args){GenericType<String>stringGenericType=newGenericType<>();stringGenericType.setT("this is a string");System.out.println(stringGenericType.getT().getClass().getSimpleName());GenericType<Long>longGenericType=newGenericType<>();longGenericType.setT(100L);System.out.printf(longGenericType.getT().getClass().getSimpleName());}}
When we run the main method, then we should see the result as below. It means, the parameter of GenericType class can be String or Long base on the type in the <> that we want when we create the GenericType class.
Java Generic Type: Java Generic Type naming convention helps us understanding code easily and having a naming convention is one of the best practices of Java programming language.
The most commonly used type parameter names are:
E - Element (used extensively by Java Collection Framework. Ex: ArrayList, Set, etc)
K - Key (Used in Map)
N - Number
T - Type
V - Value (Used in Map)
S, U, V etc - 2nd, 3rdm 4th types