Generics In Java
A generic class in Java is a class that can work with different data types while providing type safety at compile time. It allows you to define a class with type parameters (placeholders for types), which are specified when you create an object of that class/
Why use Generics?
Type Safety: Prevents runtime ClassCastException by catching type mismatches at compile time.
Code Reusability: Write a single class/method that works with any type.
Readability: No need for unnecessary type casting.
Syntax of a Generic Class
class Box<T> { // T is a type parameter
private T value;
public void set(T value) {
this.value = value;
}
public T get() {
return value;
}
}
Here:
T is a type parameter (can be replaced by any type like String, Integer, Double, etc.).
When you create an object, you specify the type.
Example Uses:
public class Main {
public static void main(String[] args) {
// Box for String
Box<String> stringBox = new Box<>();
stringBox.set("Hello Generics");
System.out.println(stringBox.get());
// Box for Integer
Box<Integer> intBox = new Box<>();
intBox.set(100);
System.out.println(intBox.get());
}
}
Output
Hello Generics
100
Commonly used type parameter names:
T – TypeE – Element(used in collections)K – KeyV – ValueN – Number
Utilities of Generic Type In Collection Framework:
Without Generic
List names = new ArrayList() ; /* Names without Generics
names can contain any type of data
that cause runtime Exception during geting same type of data */
names.add( "Deepak") ;
names.add( 123) ;
names.add( 123.50) ;
names.add( true) ;
/* By default type of below instaces are Object
but to get specific type developer needs to type caste as per the data */
String n1 = (String) names.get(0);
Integer n2 = (Integer) names.get(1);
Integer n3 = (Integer) names.get(2); // Cause Runtime ClassCaste Exception
System. out.println(n1) ; // Deepak
System. out.println(n2) ; //123
With Generic
List<String> names = new ArrayList<>();
names.add("Deepak");
names.add(123); // Compile time Error
names.add(123.50); // Compile time Error
names.add(true); // Compile time Error
String n1 = names.get(0); // No Cast Needed
System.out.println(n1);
