---
title: "Java - Generic"
author: "enlbi"
date: "2011-07-19T12:35:03Z"
tags: []
categories: ["编程语言"]
slug: "java-generic"
draft: false
lastmod: "2011-07-19T13:12:10Z"
id: 1127808
url: "https://enlbi.iteye.com/blog/1127808"
---

Generics

&lt;!--\[if !supportLists]--&gt;1.       &lt;!--\[endif]--&gt; 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

 

&lt;!--\[if !supportLists]--&gt;2.       &lt;!--\[endif]--&gt;Define a simple generics

 

public interface List &lt;E&gt;{

    void add(E x);

    Iterator&lt;E&gt; iterator();

}

 

public interface Iterator&lt;E&gt;{

    E next();

    boolean hasNext();

}

 

 

`List<?` `extends` `Shape>` is an example of a *bounded wildcard*.

 

&lt;!--\[if !supportLists]--&gt;3.   &lt;!--\[endif]--&gt;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.

 

&lt;!--\[if !supportLists]--&gt;4.   &lt;!--\[endif]--&gt;Notice

参数化 类型

List&lt;String&gt;

 

实际类型参数

String

 

泛型

List&lt;E&gt;

 

形式类型参数

E

 

无限制通配符类型

List&lt;?&gt;

 

原生态类型

List

 

有限制类型参数

&lt;E extends Number&gt;

 

 

递归类型限制

&lt;T extends  Comparable&lt;T&gt;&gt;

 

有限制通配符类型

List&lt;? Extends Number&gt;

 

泛型方法

Static &lt;E&gt; List&lt;E&gt; asList&lt;E\[] a&gt;

 

类型令牌

String.class

 

 

 

 

&lt;!--\[if !supportLists]--&gt;1）             &lt;!--\[endif]--&gt;Class literal 类文字中必须使用原生态类型，规范不允许使用参数化类型。