← Java from Scratch Lesson 83 of 88 · 10 XP

Generics

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Generics are classes and methods with a type parameter. One piece of code works for any types, and the compiler checks that the types aren't mixed up:

class Box<T> {                          // T is "some type", filled in when the object is created
    private T value;
    Box(T value) { this.value = value; }
    T get() { return value; }
}

Box<String> b = new Box<>("sword");
String s = b.get();                     // no casting

static <T extends Comparable<T>> T maxOf(List<T> list) {   // a generic method with a bound:
    T best = list.get(0);                                  // T must be comparable
    for (T x : list) if (x.compareTo(best) > 0) best = x;
    return best;
}
  • type parameters are usually named with one letter: T (type), E (element), K/V (key/value);
  • primitives can't be used: Box<int> is an error, you need Box<Integer>;
  • List<?> is a list of anything, List<? extends Number> is a list of numbers of any kind.

Under the hood. Type erasure: after compilation Box<String> and Box<Integer> are the same class Box with an Object field; only the compiler does the checks.

Task. Finish the generic Pair<A, B> (first(), second(), swap() → Pair<B, A>, toString() → (a, b)) and the method static <T extends Comparable<T>> T maxOf(List<T> list).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.