11) Generics (the useful parts)
Goal
Write type-safe reusable code (and read generic code without panic).
Why generics?
Without generics you lose type safety:
List items = new ArrayList();
items.add("hi");
Integer x = (Integer) items.get(0); // runtime crash
With generics:
List<String> items = new ArrayList<>();
items.add("hi");
String x = items.get(0);
Generic methods
static <T> T first(List<T> list) {
return list.get(0);
}
Wildcards
List<? extends Number>: list of some subtype of Number (read-only-ish)
List<? super Integer>: list of Integer or its supertype (write-friendly)
Rule of thumb: PECS
- Producer Extends
- Consumer Super
Exercises
- Implement
Box<T> with get() and set(T).
- Write a method
sum(List<? extends Number> nums) returning double.
Table of contents
- Getting Started: Install, run, and your first program
- Java Basics: types, variables, operators, formatting
- Control Flow: if/switch/loops
- Methods: parameters, return values, overloading
- OOP: classes, objects, encapsulation
- Inheritance & Polymorphism (and when not to use them)
- Interfaces, abstract classes, and design basics
- Exceptions and error handling
- Strings, files, and I/O basics
- Collections: List/Set/Map and Big-O intuition
- Generics (the useful parts)
- Lambdas & Streams
- Dates and time (java.time)
- Testing with JUnit 5 (basics)
- Concurrency: threads, executors, futures
- JVM basics: memory, GC, performance habits
- Build tools: Maven essentials (recommended)
- Next steps: projects to build