Generics
Type-safe containers.
Generics
Analogy: label
Generics are like Labels on Boxes.
If you label a box "Books", you shouldn't be able to put a "Sandwich" in it.
Without Generics, every box is a "Mystery Box" (Object), and you might get a nasty surprise when you reach in!
The Magic Box
Define the type of the box (<T>) and see what fits.
- Box<String>: Only accepts text.
- Box<Integer>: Only accepts numbers.
- Box<Fruit>: Only accepts fruit.
Magic Box (Generics)
1. Define Box Type <T>
2. Try to Insert Item
Box<String>
The Code
Use angle brackets <T> to define a generic type.
Java Example
Switch language in Navbar
// A Generic Class
class Box<T> {
private T content;
public void set(T content) { this.content = content; }
public T get() { return content; }
}
Box<String> stringBox = new Box<>();
stringBox.set("Hello"); // OK
// stringBox.set(123); // Compile Error!
Advanced Concepts
Bounded Types
Sometimes you want to restrict what types can be used.
- Upper Bound:
<T extends Number>(Must be Number or subclass).
Java Example
Switch language in Navbar
// Only accepts Numbers (Integer, Double, etc.)
class Calculator<T extends Number> {
// ...
}
Wildcards
When you don't know the exact type.
- Unbounded:
<?>(Any type). - Upper Bounded:
<? extends Number>(Number or subclass). - Lower Bounded:
<? super Integer>(Integer or superclass).
Java Example
Switch language in Navbar
// Wildcard: ? means "Any Type"
void printBox(Box<?> box) {
System.out.println(box.get());
}
Up Next
Enums