Cypress PDF
Cypress PDF
Cypress PDF
The Java Generics programming was introduced in Java 5 to deal with type-safe objects.
Now what do we mean by Type-Safety?
Type Erasure:- When Java compiler sees code written using Generics it completely erases that code and convert it into raw type
i.e. code without Generics. All type related information is removed during erasing. So your ArrayList<Gold> becomes plain
old ArrayList prior to JDK 1.5, formal type parameters e.g. <K, V> or <E> gets replaced by
either Object or Super class of the Type.
// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}
obj.print();
}
}
Generic Method:-
We can also write generic method that can be called with different types of arguments based on the type of
arguments passed to generic method, the compiler handles each method.
// A Simple Java program to show working of user defined
// Generic method
class Test
{
// A Generic method example
static <T> void genericDisplay (T element)
{
System.out.println(element.getClass().getName() +
" = " + element);
}
// Driver method
public static void main(String[] args)
{
// Calling generic method with Integer argument
genericDisplay(11);