Lesson 6 of 10
Generics - Type Safety & Reuse
Generics let you write classes and methods that work with any type while maintaining strong type safety at compile time. Without generics, you'd need casts everywhere and get ClassCastException at runtime. Generics eliminate this through type parameterisation.
Generic Classes, Methods & Bounded Wildcards
// Generic class - T is the type parameter
public class Pair<A, B> {
private final A first;
private final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public A getFirst() { return first; }
public B getSecond() { return second; }
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
// Generic method - can be static
public class GenericUtils {
// T must extend Comparable<T> - bounded type parameter
public static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) >= 0 ? a : b;
}
// Wildcard: ? extends T - upper bounded (read from collection of T or subtypes)
public static double sumList(List<? extends Number> numbers) {
double sum = 0;
for (Number n : numbers) sum += n.doubleValue();
return sum;
}
// Wildcard: ? super T - lower bounded (write T into collection that accepts T or supertypes)
public static void addNumbers(List<? super Integer> list) {
list.add(1);
list.add(2);
list.add(3);
}
public static void main(String[] args) {
// Generic class usage
Pair<String, Integer> entry = new Pair<>("Alice", 42);
String name = entry.getFirst(); // no cast needed!
int score = entry.getSecond();
System.out.println(entry); // (Alice, 42)
// Generic method usage - type inferred from arguments
System.out.println(GenericUtils.max(10, 20)); // 20
System.out.println(GenericUtils.max("Alice", "Bob")); // Bob (alphabetical)
// Bounded wildcards - PECS: Producer Extends, Consumer Super
List<Integer> ints = List.of(1, 2, 3);
List<Double> doubles = List.of(1.5, 2.5, 3.5);
System.out.println(sumList(ints)); // 6.0 - Integer extends Number
System.out.println(sumList(doubles)); // 7.5 - Double extends Number
// Type erasure - generics are compile-time only
List<String> strings = new ArrayList<>();
List<Integer> integers = new ArrayList<>();
System.out.println(strings.getClass() == integers.getClass()); // true!
// At runtime both are just ArrayList (type info erased)
}
}Quick Quiz
Tip
Tip
Practice Generics Type Safety Reuse in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Generics - Type Safety & Reuse
Practice Task
Note
Practice Task - (1) Write a working example of Generics Type Safety Reuse from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Generics Type Safety Reuse is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?