---
title: "定义泛型接口和类"
author: "runfeel"
date: "2013-07-09T09:11:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2013-07-11T13:33:56Z"
id: 1903644
url: "https://runfeel.iteye.com/blog/1903644"
---

# JDK1.5之后的List接口，Iterator接口，Map接口的代码：

# public interfaceList&lt;E&gt;

# {

# voidadd(E x);

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

# }

# public interfaceIterator&lt;E&gt;

# {

# E next();

# Boolean hasNext();

# }

# Public interfaceMap&lt;K,V&gt;

# {

# Set&lt;K&gt; keyset();

# V put(K key, V value);

# }

# 上面三个接口声明比较简单，除了尖括号中的内容――这就是泛型的实质；允许在定义接口，类时指定类型形参，类型形参在整个接口，类体内中可当作类型使用，几乎所有可使用其他普通类型的地方都可以使用这种类型形参。

# 例如我们使用List类型时，为E形参传入String类型实参，则产生了一个新的类型： List&lt;String&gt;类型，我们可以把List&lt;String&gt;想像成E杯全部替换成String的特殊List子接口：

# Public interfaceListString extends List

# {

# Voidadd(String x);

# Iterator&lt;String&gt; iterator();

# }

# 虽然程序只定义了一个List&lt;E&gt;接口，但实际使用时可以产生无数多个List接口，只要为E传入不同的类型实参，系统就会多出一个新的List子接口。

**public class** Apple&lt;T&gt; {

**private** T info;

**public** Apple(){}

**public** Apple(T info){

**this**.info =info;

}

**public void** setInfo(T info){

**this**.info =info;

}

**public** T getInfo(){

**return this**.info;

}

**public static void** main(String\[] args){

Apple&lt;String&gt; a1 = **new** Apple&lt;String&gt;("Apple");

System.*out*.println(a1.getInfo());

Apple&lt;Double&gt; a2 = **new** Apple&lt;Double&gt;(2.00);

System.*out*.println(a2.getInfo());

}

# }

# Output:

Apple

# 2.0

# 上面定义了一个带泛型声明的Apple&lt;T&gt;类，实际使用时会为T形参传入实际类型。