Generics

Parameterised types: a collection of a given type, generic classes and methods, type checking at compile time, wrapper types and the bound of a type parameter.

  • 24 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • Generics: what is it?

    Show the answer

    A mechanism that writes a class or method once for types chosen at the point of use, with the compiler checking them.

    List<String> and List<Integer> come from the same class List<E>. Without it, you would need one class per type or Object everywhere, with risky casts.

  • What does the compiler answer to names.add(3); when names is a List<String>?

    • incompatible types: int cannot be converted to String
    • Nothing: 3 is converted to "3" and added
    • ClassCastException at run time, when the element is read back
    • cannot find symbol : method add(int)
    Show the answer

    incompatible types: int cannot be converted to String

    The type String is known at compile time, so the error is reported at the faulty line. Java does not convert an int to a String on the programmer's behalf; you would write String.valueOf(3).

  • A type parameter must be a …: write List<…> and never List<int>.

    Show the answer

    A type parameter must be a class: write List<Integer> and never List<int>.

    The compiler answers "unexpected type, required: reference, found: int". The wrapper of double is Double, of boolean is Boolean, of char is Character.

  • Type parameter: what is it?

    Show the answer

    A name, often T, E or K, that stands in a class or method for a type not yet known, fixed at the point of use.

    class Box<T> declares T; new Box<String>(...) fixes it to String. Inside the class, T is written like a type: attribute T value, return T get().

  • A Stack class must hold integers in one program and strings in another, with type checking at compile time. Which design should you choose?

    • A Stack class holding Object, with a cast on reading
    • A generic class Stack<T>
    • Two copied classes, IntStack and StringStack
    • A Stack class holding String that converts the integers
    Show the answer

    A generic class Stack<T>

    Stack<T> is written once and the compiler checks each use. The Object version compiles but defers errors to run time; two copied classes double the maintenance for no gain.