JAVA — CHAPTER 13

Generic Classes and Methods: A Deeper Look · Cheat Sheet
Generic Methods Type Erasure Generic Classes Wildcards
1 WHY GENERIC METHODS?

The problem without generics

You'd need a separate overloaded printArray for int[], double[], String[] … — repetitive, hard to maintain.

public static <T> void printArray(T[] arr) { for (T item : arr) System.out.print(item + " "); } // works for Integer[], String[], any object array
2 IMPLEMENTATION & COMPILE-TIME TRANSLATION

<T> — the type parameter

  • Declared right before the return type: <T> void method(T x)
  • Acts as a placeholder the compiler fills in per call
  • Common names: T (Type), E (Element), K,V (Key,Value)

Type erasure

At compile time, generic type info is used for checking, then largely erased — the compiled bytecode mostly just uses Object, with the compiler inserting the right casts automatically.

3 RETURNING A TYPE PARAMETER & OVERLOADING
public static <T> T max(T a, T b, Comparator<T> cmp) { return cmp.compare(a, b) > 0 ? a : b; }

Overloading generic methods

Just like regular methods, generic methods can be overloaded by having different parameter lists (e.g. one version taking two Ts, another taking three).

4 GENERIC CLASSES
public class Stack<T> { private List<T> items = new ArrayList<>(); public void push(T item) { items.add(item); } public T pop() { return items.remove(items.size()-1); } } // usage: Stack<String> s = new Stack<>();

Why generic classes?

Write the class logic once (like a custom Stack<T> or Pair<K,V>) and reuse it safely with any object type, with the compiler enforcing consistency.

5 WILDCARDS — ? extends AND ? super
WildcardMeaning
List<?>list of unknown type — read-only
List<? extends Number>Number or any subclass — safe to read
List<? super Integer>Integer or any superclass — safe to write
public static double sum(List<? extends Number> list) { double total = 0; for (Number n : list) total += n.doubleValue(); return total; }
6 GENERIC SYNTAX QUICK REFERENCE
SyntaxMeaning
<T> void method(T x)generic method with type parameter T
<T extends Comparable<T>>bounded type parameter — T must implement Comparable
class Box<T> { }generic class with type parameter T
class Pair<K,V> { }generic class with two type parameters
List<?>unbounded wildcard — unknown element type
List<? extends T>upper-bounded wildcard — read-only producer
List<? super T>lower-bounded wildcard — write-safe consumer