Skip to content

Instantly share code, notes, and snippets.

@cb341
Created January 2, 2026 11:57
Show Gist options
  • Select an option

  • Save cb341/3538178951ac02b9c93efdce6fe56b65 to your computer and use it in GitHub Desktop.

Select an option

Save cb341/3538178951ac02b9c93efdce6fe56b65 to your computer and use it in GitHub Desktop.
Problems and Solutions with Java Generics (?)
// 1. RUNTIME ERRORS (RAW TYPES)
// PROBLEM
List list = new ArrayList();
list.add(99);
String s = (String) list.get(0); // ClassCastException at runtime!
// SOLUTION
List<Integer> list = new ArrayList<>();
list.add(99);
// list.add("a"); // Compiler Error: Prevents the crash immediately
// 2. PASSING SUBTYPES (INVARIANCE)
// PROBLEM: List<Circle> is NOT a List<Figure>
void draw(List<Figure> f) { ... }
List<Circle> circles = new ArrayList<>();
// draw(circles); // Compiler Error
// SOLUTION: Use "? extends" for READ-ONLY access
void draw(List<? extends Figure> f) {
Figure fig = f.get(0); // OK to read
// f.add(new Circle()); // Compiler Error: Cannot write
}
// 3. ADDING TO LISTS (LOWER BOUNDS)
// PROBLEM: Cannot add to a list with "? extends"
void addRect(List<? extends Figure> list) {
// list.add(new Rectangle()); // Compiler Error: Type unknown
}
// SOLUTION: Use "? super" for WRITE access
void addRect(List<? super Rectangle> list) {
list.add(new Rectangle()); // OK
}
// 4. GENERIC ARRAYS
// PROBLEM: Erasure prevents direct allocation
// T[] a = new T[10]; // Compiler Error
// SOLUTION: Allocate Object[] and cast
@SuppressWarnings("unchecked")
T[] a = (T[]) new Object[10]; // OK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment