Generics (Java)
Generics let you write classes and methods that work with any type while keeping type safety. You specify the type in angle brackets, like ArrayList<String>, so the compiler can catch type mistakes early.
Java
Before generics, collections held plain Objects and you had to cast values manually, risking runtime errors. Generics move that checking to compile time and remove the need for casts.
The letter inside the brackets when defining a generic (like <T>) is a type parameter — a placeholder filled in when the code is used.
Examples
Java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
nums.add(5);
int first = nums.get(0); // no cast needed
System.out.println(first);
}
}Output:
5