Generics Flashcards
they add stability to your code by making more of your bugs detectable at compile time
generics
They provide a way for you to re-use the same code with different inputs
type parameters
Why use generics?
- stronger type checks at compile time
- elimination of casts
- enable programmers to implement generic algorithms
This is a generic class or interface that is parameterized over types
class name<T1, T2, …, Tn> { /* … */ }
generic type
You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond.
Box<Integer> integerBox = new Box<>();</Integer>
The Diamond.
The name of a generic class or interface without any type arguments.
Raw Types
These are methods that introduce their own type parameters.
a type parameter before the return type of the
method declaration. This is needed even if the method is returning void.
Generic methods
methods are used to restrict the number of types of data for a class
Bounded Type
Parameters
a Java compiler’s ability to look at each method
invocation and corresponding declaration to determine the type
argument (or arguments) that make the invocation applicable.
Type inference
determines the types of the arguments and, if
available, the type that the result is being assigned, or returned.
tries to find the most specific type that
works with all of the arguments.
The inference algorithm
represents
an unknown type.
Wildcards ?
never used as a type argument for a generic method
invocation, a generic class instance creation, or a supertype.
wildcard
relax the restrictions on a variable.
restricts to its
sub-type.
Upper Bounded Wildcards.
List<? extends Number>
a list of unknown
type.
public static void printList(List<?> list) {
Unbounded Wildcards
<? super A>.
restricts the unknown type to be a specific type or a super-type
Lower Bounded Wildcards.
What does type erasure do?
- replace all type parameters in generic types with their bounds or object if the type parameters are unbounded.
- insert type casts if necessary to preserve type safety
- generate bridge methods to preserve polymorphism in extended generic types
It ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.
Type Erasure