abstract over type
-
type parameter
类型参数 compile-time
public interface List<E> {
void add(E x);
Iterator<E> iterator();
}
formal type parameters
actual type argument
- A generic type declaration is compiled once and for all,
-
List<String>
不是List<Object>
的subtype
wildcard type
-
Collection<?>
(pronounced "collection of unknown") - 使用
generic method
解决compile-time error
- The compiler infers the most specific type argument
-
erasure
类型擦除 - 泛型类Class不包含泛型参数。运行时没有类型参数。
- 不能新建泛型数组。
-
? extends T
和? super T
<T> T[] makeArray(T t) {
return new T[100]; // Error.
}
In general, if you have an API that only uses a type parameter T as an argument, its uses should take advantage of lower bounded wildcards (? super T). Conversely, if the API only returns T, you'll give your clients more flexibility by using upper bounded wildcards (? extends T).
multiple bounds
T1 & T2 ... & Tn
A type variable with multiple bounds is known to be a subtype of all of the types listed in the bound.