For m ore
awesom
Java Generics cheat sheet vis it rebe e cheat s heets
ll abs.org!
Basics Producer Extends Consumer Super (PECS) Method Overloading
Generics don’t exist at runtime! Collections.copy(List<? super T> dest, List<? extends T> src) String f(Object s) {
return "object";
class Pair<T1, T2> { /* ... */ } src -- contains elements of type T or its subtypes. }
-- the type parameter section, in angle String f(String s) {
dest -- accepts elements, so defined to use T or its supertypes. return "string";
brackets, specifies type variables.
}
Type parameters are substituted when <T> String generic(T t) {
Consumers are contravariant (use super). Producers are covariant (use extends).
objects are instantiated. return f(t);
}
Pair<String, Long> p1 = new
Pair<String, Long> ("RL", 43L); If called generic("string") returns "object".
Avoid verbosity with the diamond operator:
Pair<String, Long> p1 =
Recursive generics
new Pair<>("RL", 43L); Recursive generics add constraints to
your type variables. This helps the compiler
to better understand your types and API.
Wildcards
interface Cloneable<T extends
Collection<Object> - heterogenous,
Cloneable<T>> {
any object goes in.
T clone();
Collection<?> - homogenous collection
}
of arbitrary type.
Now cloneable.clone().clone()
Avoid using wildcards in return types! will compile.
Intersection types Covariance
<T extends Object & List<Number> > ArrayList<Integer>
Comparable<? super T>> T
max(Collection<? extends T> coll) Collections are
not covariant!
The return type here is Object!
Compiler generates the bytecode
for the most general method only.