Java Generics: Type-Safe Containers
A box of Object takes "Java Basics" and 42, and the String cast on the way out crashes. Box<T> lets the label decide what goes in, so javac stops the 42 before the program runs. Plus Pair<K, V>, the diamond, type erasure and a raw list next to a typed one.
What you will learn
- Explain why a box of Object needs casts and can crash with ClassCastException
- Write a generic class Box<T> and use it with different types
- Use two type parameters and the diamond operator
- Explain type erasure and why a typed list fails at compile time instead of run time
Before you start
- Java ArrayList
- Java wrapper classes and autoboxing
The whole idea of generics fits in one line: the label on the box decides what may go in. To see why that matters, start with a box that has no label.
A box that takes anything
package org.studyeasy.s04l05;
// The old way: one box for anything
public class ObjectBox {
private Object item;
public void set(Object item) {
this.item = item;
}
public Object get() {
return item; // you get back a plain Object
}
}
ObjectBox box = new ObjectBox();
box.set("Java Basics");
String title = (String) box.get(); // cast every time
System.out.println("Course: " + title);
box.set(42); // compiler says fine
try {
String oops = (String) box.get(); // 42 is not a String
System.out.println(oops);
} catch (ClassCastException e) {
System.out.println("Crash: "
+ e.getClass().getSimpleName());
}
Course: Java Basics
Crash: ClassCastException
Object is the parent of every class, so the box holds anything. That's the problem. get returns a plain Object, so every read needs a cast. The 42 goes in without complaint, and the String cast on the way out fails because it's an Integer inside. You only find out while the program runs; without the catch, Java stops with the ClassCastException.
The label decides what may go in
package org.studyeasy.s04l05;
// T is a type parameter: the caller picks the real type
public class Box<T> {
private T item;
public void set(T item) {
this.item = item;
}
public T get() {
return item; // comes back as T, no cast
}
}
T is a type parameter, a placeholder for the real type. Write Box<String> and T becomes String: that's the label.
Box<String> course = new Box<>();
course.set("Java Basics");
String title = course.get(); // no cast
System.out.println("Course: " + title);
Box<Integer> seats = new Box<>();
seats.set(30);
int left = seats.get() - 4; // unboxed to int
System.out.println("Seats left: " + left);
boolean same = course.getClass() == seats.getClass();
System.out.println("Same class at runtime? " + same);
Course: Java Basics
Seats left: 26
Same class at runtime? true
Box<String> takes only Strings, and get already returns a String. Box<Integer> takes only Integers; 30 comes back and is unboxed, so 30 minus 4 is 26. Add course.set(42) and javac stops: int cannot be converted to String. The 42 never gets into the box.
Why is "same class" true? Javac checks the labels while compiling, then erases them. This is called type erasure. At run time both boxes are the same Box class. The labels are for the compiler.
Two parameters, and the diamond
package org.studyeasy.s04l05;
// Two type parameters: K for the key, V for the value
public class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
public String toString() {
return key + "=" + value;
}
}
Pair<String, Integer> asha =
new Pair<String, Integer>("Asha", 87); // spelled out
Pair<String, Integer> ben = new Pair<>("Ben", 92); // diamond
System.out.println(ben.getKey() + " scored " + ben.getValue());
List<Pair<String, Integer>> grades = new ArrayList<>();
grades.add(asha);
grades.add(ben);
System.out.println("Grades: " + grades);
Ben scored 92
Grades: [Asha=87, Ben=92]
Each type parameter gets its own label: K becomes String and V becomes Integer. For Asha the types are written out in full; for Ben the empty angle brackets, the diamond, let Java copy them from the left side. getKey returns a String and getValue an Integer, with no casts anywhere. new Pair<>("Cara", "high") fails, because "high" isn't an Integer.
Where does the 42 get caught?
List raw = new ArrayList(); // no type: anything goes
raw.add("Asha");
raw.add(42); // compiler says fine
try {
for (Object o : raw) {
String name = (String) o;
System.out.println("Student: " + name);
}
} catch (ClassCastException e) {
System.out.println("Crash: "
+ e.getClass().getSimpleName());
}
List<String> names = new ArrayList<>();
names.add("Asha");
names.add("Ben");
System.out.println("Typed: " + names);
Student: Asha
Crash: ClassCastException
Typed: [Asha, Ben]
(The real file puts @SuppressWarnings({"rawtypes", "unchecked"}) on main to quiet the compiler's warnings about the raw list.)
The raw List has no label, so Asha and 42 both go in, and the cast in the loop breaks on 42 at run time. List<String> checks every add, so names.add(42) is a compile error: incompatible types. A compile error is the better kind, because a run-time error can reach your users.
Recap
| Idea | Example |
|---|---|
| Box of Object | takes anything; every read needs a cast; wrong cast crashes at run time |
| Generic class | class Box<T>; the caller picks T |
| Two parameters | Pair<K, V> |
| Diamond | new Pair<>("Ben", 92) |
| Type erasure | labels are checked, then erased: one Box class at run time |
Next: methods with their own type parameter, bounds and wildcards in generic methods, bounded types and wildcards.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)