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.
- Concepts
- Questions
- Sort and link
- 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>andList<Integer>come from the same classList<E>. Without it, you would need one class per type orObjecteverywhere, with risky casts.What does the compiler answer to
names.add(3);whennamesis aList<String>?incompatible types: int cannot be converted to String- Nothing:
3is converted to"3"and added ClassCastExceptionat run time, when the element is read backcannot find symbol : method add(int)
Show the answer
incompatible types: int cannot be converted to StringThe type
Stringis known at compile time, so the error is reported at the faulty line. Java does not convert anintto aStringon the programmer's behalf; you would writeString.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
doubleisDouble, ofbooleanisBoolean, ofcharisCharacter.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>declaresT;new Box<String>(...)fixes it toString. Inside the class,Tis written like a type: attributeT value, returnT get().A
Stackclass must hold integers in one program and strings in another, with type checking at compile time. Which design should you choose?- A
Stackclass holdingObject, with a cast on reading - A generic class
Stack<T> - Two copied classes,
IntStackandStringStack - A
Stackclass holdingStringthat converts the integers
Show the answer
A generic class
Stack<T>Stack<T>is written once and the compiler checks each use. TheObjectversion compiles but defers errors to run time; two copied classes double the maintenance for no gain.- A