Generics
Type safety is key! Learn how to write flexible and reusable code with Generics.
Type safety is key! Learn how to write flexible and reusable code with Generics. This hands-on tutorial focuses on practical implementation of generics concepts.
Generics
Generics allow you to create classes, interfaces, and methods that take a type as a parameter (like ArrayList<T>).
It provides stronger compile-time type checks and eliminates the need for manual casting.
Without Generics
Before Java 5, collections held Object types.
List list = new ArrayList();
list.add("Hello");
String s = (String) list.get(0); // Casting required
With Generics
List<String> list = new ArrayList<>();
list.add("Hello");
String s = list.get(0); // No casting!
Creating a Generic Class
public class Box<T> {
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
Usage
Box<Integer> integerBox = new Box<>();
integerBox.set(10);
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
Bounded Type Parameters
You can restrict the types that can be used.
public class NumberBox<T extends Number> { ... }
Now T can only be Integer, Double, etc.
Interactive Code
Create a Generic Printer!
AI Mentor
Confused about "Java Generics: classes, methods and wildcard usage"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3What is the main benefit of Generics?
Next Steps
Next, let's look at a special data type: Enums.