Generics
Generics
Generics
Java 11 (1Z0-819)
2
Copyright Seán Kennedy.
Generics
• Generics were introduced in Java 1.5
3
Copyright Seán Kennedy.
Generics
• A container that stores Object types has a critical weakness
- type information is lost. This means that you must provide a
cast when retrieving elements from the container. In addition
and more importantly, the compiler is unable to determine if
the cast is correct - a coding error. This results in a
ClassCastException at runtime.
4
Copyright Seán Kennedy.
Generics
• Generics will ensure that any attempt to add a type other
than the particular type specified will be caught at compile
time. This is known as “type-safety”.
5
Copyright Seán Kennedy.
6
Copyright Seán Kennedy.
Type Erasure
• Pre-generics, Java used Object types in collections.
7
Copyright Seán Kennedy.
Polymorphism and Generics
• Polymorphism applies to the base type:
• List<Integer> myList = new ArrayList<Integer>();
• Issue:
8
Copyright Seán Kennedy.
10
Copyright Seán Kennedy.
Wildcard Generic Type
• To solve the polymorphism issue for generics, we use the
wildcard question mark symbol i.e. ?.
11
Copyright Seán Kennedy.
Unbounded wildcard
12
Copyright Seán Kennedy.
Bounded Wildcards
13
Copyright Seán Kennedy.
extends
• Downward syntax is:
• someMethod(List<? extends Number> list)
• list is a method parameter that can handle lists of
Number, Integer, Double etc...
• note, that in this context, extends is used in a
general sense to mean “extends” (as in classes)
but also “implements” (as in interfaces).
• known as “upper bounded wildcards” - restricts the
unknown type to be a specific type or a subtype of
that type
• read-only
14
Copyright Seán Kennedy.
super
• Upward syntax is:
• someMethod(List<? super Integer> list)
• list is a method parameter that can handle lists of
Integer or any super type of Integer
15
Copyright Seán Kennedy.
Generic Classes
• We can add generics to our own types (classes and
interfaces).
17
Copyright Seán Kennedy.
Naming Conventions
• Can be anything but the convention is to use single
uppercase letters.
• N is a number
18
Copyright Seán Kennedy.
Multiple types.
19
Copyright Seán Kennedy.
Generic Interfaces
• Interfaces can declare formal type parameters also.
20
Copyright Seán Kennedy.
Generic interfaces.
21
Copyright Seán Kennedy.
Generic Methods
• Formal type parameters can also be used on methods.
22
Copyright Seán Kennedy.
Generic methods.
23
Copyright Seán Kennedy.