Advanced Java · Lesson 89 of 150
Generics
Generics allow you to write classes, interfaces, and methods that work with a specific type you decide when you actually use them, instead of fixing the type in advance. This is written using angle brackets, like <T>.
01What are Generics?
Generics allow you to write classes, interfaces, and methods that work with a specific type you decide when you actually use them, instead of fixing the type in advance. This is written using angle brackets, like <T>.
02Why is it used?
Generics allow the same class or method to work safely with different data types, while still catching type-related mistakes at compile-time, rather than causing unexpected errors while the program is running.
03Real-Life Example
Think of a universal container that can be labeled to hold exactly one specific kind of item at a time — sometimes fruits, sometimes books — but once labeled, it strictly enforces that only that kind of item goes inside.
04Syntax
javaclass ClassName<T> { T value; } ClassName<String> obj = new ClassName<>();
05Example Program
javaclass Box<T> { T item; void setItem(T item) { this.item = item; } T getItem() { return item; } } public class GenericsDemo { public static void main(String[] args) { Box<String> box = new Box<>(); box.setItem("Java Book"); System.out.println("Item: " + box.getItem()); } }
Output:
Item: Java Book06Key Points to Remember
- Generics catch type mismatches at compile-time, avoiding many runtime errors.
<T>is just a placeholder name — common conventions includeTfor type,Efor element,K/Vfor key/value.- Collections like
ArrayList<Integer>already use generics internally, which is why they only allow one specified type of element.