ITEEDU

泛型类实例

可以在定义泛型类别时,宣告多个类型持有者,例如:

GenericFoo.java
public class GenericFoo<T1, T2> {
	private T1 foo1;
	private T2 foo2;
	public void setFoo1(T1 foo1) {
		this.foo1 = foo1;
	}
	public T1 getFoo1() {
		return foo1;
	}
	public void setFoo2(T2 foo2) {
		this.foo2 = foo2;
	}
	public T2 getFoo2() {
		return foo2;
	}
}

您可以如下使用GenericFoo类别,分别以Integer与Boolean取代T1与T2:

GenericFoo<Integer, Boolean> foo =new GenericFoo<Integer, Boolean>();

如果是数组的话,可以像这样:

GenericFoo.java
public class GenericFoo<T> {
	private T[] fooArray;
	public void setFooArray(T[] fooArray) {
		this.fooArray = fooArray;
	}
	public T[] getFooArray() {
		return fooArray;
	}
}

您可以像下面的方式来使用它:

String[] strs = {"caterpillar", "momor", "bush"};

GenericFoo<String> foo = new GenericFoo<String>();
foo.setFooArray(strs);
strs = foo.getFooArray();