Generics in Collections in Java
Generics let a class or method be written once but work with any type, specified in angle brackets at the point of use — ArrayList<String> is an ArrayList specifically of String elements, and ArrayList<Integer> is a completely separate specialization of that same general-purpose class. The compiler checks generic type usage at compile time and enforces it: attempting to add an Integer to an ArrayList<String> simply fails to compile, catching an entire category of mistake before the program ever runs.
Before generics existed, pre-Java 5, collections stored plain Object references and needed an explicit cast every time an element was retrieved, with no compile-time guarantee the cast would actually succeed. Generics remove both the manual casting and that runtime risk in one change.
The angle-bracket syntax
ArrayList<String> declares an ArrayList specifically restricted to holding String elements.
Compile-time type checking
Adding an element of the wrong type to a generic collection fails to compile, rather than failing only once the program runs.
No manual casting needed
Retrieving an element from a generic collection already comes back as the declared type, with no cast required.
Before generics (pre-Java 5)
Collections stored plain Object, requiring an explicit cast on every retrieval, with no compile-time safety net if that cast was wrong.
Generic type parameters can be almost any class
Including custom ones a program defines itself, not just built-in types like String or Integer.
import java.util.ArrayList; public class GenericsDemo { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); names.add("Ana"); String first = names.get(0); System.out.println("First name: " + first); System.out.println("Length: " + first.length()); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.