Created
January 2, 2026 11:57
-
-
Save cb341/3538178951ac02b9c93efdce6fe56b65 to your computer and use it in GitHub Desktop.
Problems and Solutions with Java Generics (?)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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