IntermediateLesson 12 of 16
Optional & Generics – Java
Handling null safely and writing type-safe, reusable classes and methods.
null is Java's "billion-dollar trap": if you call a method on null, you get a NullPointerException. Optional<T> makes a possibly missing result visible in the type.
import java.util.*;
static Optional<String> findeEmail(Map<String, String> db, String name) {
return Optional.ofNullable(db.get(name));
}
var db = Map.of("ada", "ada@example.com");
System.out.println(findeEmail(db, "ada").map(String::toUpperCase).orElse("unknown")); // ADA@EXAMPLE.COM
System.out.println(findeEmail(db, "bob").orElse("unknown")); // unknown
findeEmail(db, "ada").ifPresent(m -> System.out.println("Sending to " + m));
System.out.println(findeEmail(db, "bob").isPresent()); // falseWarningUse
Optional as a return type, not for fields or parameters. Never call get() without checking – use orElse, orElseGet, orElseThrow or map/ifPresent.Generics parameterize types: List<String> can only hold strings, and the compiler checks this. You can write your own generic classes and methods and restrict types (extends).
class Paar<A, B> {
private final A erstes;
private final B zweites;
Paar(A erstes, B zweites) { this.erstes = erstes; this.zweites = zweites; }
A erstes() { return erstes; }
B zweites() { return zweites; }
}
static <T extends Comparable<T>> T maximum(List<T> liste) {
T max = liste.get(0);
for (T x : liste) {
if (x.compareTo(max) > 0) max = x;
}
return max;
}
var p = new Paar<>("Ada", 36);
System.out.println(p.erstes() + " " + p.zweites()); // Ada 36
System.out.println(maximum(List.of(3, 9, 4))); // 9
System.out.println(maximum(List.of("pear", "apple"))); // pearWildcards describe flexible parameters: List<? extends Number> reads any list of numbers, List<? super Integer> writes Integers into suitable lists (mnemonic PECS: Producer Extends, Consumer Super).
static double summe(List<? extends Number> zahlen) {
double s = 0;
for (Number n : zahlen) s += n.doubleValue();
return s;
}
System.out.println(summe(List.of(1, 2, 3))); // 6.0
System.out.println(summe(List.of(1.5, 2.5))); // 4.0TipType erasure: generic type information exists only at compile time. At runtime
List<String> is simply List – which is why new T() or instanceof List<String> are not allowed.