ITEEDU

Java Gossip: 限制泛型可用类型

在定义泛型类别时,预设您可以使用任何的型态来实例化泛型类别中的型态持有者,但假设您想要限制使用泛型类别时,只能用某个特定型态或其子类别才能实例化型态持有者的话呢?

您可以在定义型态持有者时,一并使用"extends"指定这个型态持有者必须是扩充某个类型,举个实例来说:

ListGenericFoo.java
import java.util.List;
public class ListGenericFoo<T extends List> {
	private T[] fooArray;
	public void setFooArray(T[] fooArray) {
		this.fooArray = fooArray;
	}
	public T[] getFooArray() {
		return fooArray;
	}
}

ListGenericFoo在宣告类型持有者时,一并指定这个持有者必须扩充自List接口(interface),在限定持有者时,无论是要限定的对 象是接口或类别,都是使用"extends"关键词。

您使用"extends"限定型态持有者必须是实作List的类别或其子类别,例如LinkedList与ArrayList,下面的程序是合法的:

ListGenericFoo<LinkedList> foo1 =new ListGenericFoo<LinkedList>();
ListGenericFoo<ArrayList> foo2 =new ListGenericFoo<ArrayList>();

但是如果不是List的类别或是其子类别,就会发生编译错误,例如下面的程序通不过编译:

ListGenericFoo<HashMap> foo3 =new ListGenericFoo<HashMap>();

编译器会回报以下错误讯息:

type parameter java.util.HashMap is not within its bound
ListGenericFoo<HashMap> foo3 = new ListGenericFoo<HashMap>();

HashMap并没有实作List界面,所以无法用来实例化型态持有者,事实上,当您没有使用extends关键词限定型态持有者时,预设则是Object下的所有子类别都可以实例化型态持有者,即只写<T>时就相当于<T extends Object>。