Generics
<!--[if !supportLists]-->1. <!--[endif]--> Functions:
The compiler can now check the type correctness of the program at compile-time.
A generic type declaration is compiled once and for all, and turned into a single class file, just like an ordinary class or interface declaration
<!--[if !supportLists]-->2. <!--[endif]-->Define a simple generics
public interface List <E>{
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E>{
E next();
boolean hasNext();
}
List<? extends Shape> is an example of a bounded wildcard.
<!--[if !supportLists]-->3. <!--[endif]-->WildCard
? 无限制的通配符(unbounded wildcard)---不确定或者不关心实际的类型参数
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).
this situation arises relatively frequently, there is a special rule that allows such code under very specific circumstances in which the code can be proven to be safe. This rule, known as wildcard capture, allows the compiler to infer the unknown type of a wildcard as a type argument to a generic method.
<!--[if !supportLists]-->4. <!--[endif]-->Notice
|
参数化 类型 |
List<String> |
|
|
实际类型参数 |
String |
|
|
泛型 |
List<E> |
|
|
形式类型参数 |
E |
|
|
无限制通配符类型 |
List<?> |
|
|
原生态类型 |
List |
|
|
有限制类型参数 |
<E extends Number>
|
|
|
递归类型限制 |
<T extends Comparable<T>> |
|
|
有限制通配符类型 |
List<? Extends Number> |
|
|
泛型方法 |
Static <E> List<E> asList<E[] a> |
|
|
类型令牌 |
String.class |
|
|
|
|
|
<!--[if !supportLists]-->1) <!--[endif]-->Class literal 类文字中必须使用原生态类型,规范不允许使用参数化类型。
本文深入探讨了Java泛型的基本概念,包括泛型类型声明、泛型接口与方法、通配符的使用及其类型检查机制。此外,还介绍了参数化类型、实际类型参数等关键概念,并解释了如何利用泛型提高程序的灵活性与安全性。
321

被折叠的 条评论
为什么被折叠?



