您可以在定義泛型類別時,宣告多個類型持有者,例如:
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>();
如果是陣列的話,可以像這樣:
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();
來改寫一下 Object 類別 中的
SimpleCollection:
public class SimpleCollection<T> { private T[] objArr; private int index = 0; public SimpleCollection() { objArr = (T[]) new Object[10]; // 預設10個物件空間 } public SimpleCollection(int capacity) { objArr = (T[]) new Object[capacity]; } public void add(T t) { objArr[index] = t; index++; } public int getLength() { return index; } public T get(int i) { return (T) objArr[i]; } }
現在您可以直接使用它來當作特定類型物件的容器,例如:
public class Test { public static void main(String[] args) { SimpleCollection<Integer> c = new SimpleCollection<Integer>(); for(int i = 0; i < 10; i++) { c.add(new Integer(i)); }
for(int i = 0; i < 10; i++) { Integer k = c.get(i); } } }
另一個SimpleCollection的寫法也可以如下,作用是一樣的:
public class SimpleCollection<T> { private Object[] objArr; private int index = 0; public SimpleCollection() { objArr = new Object[10]; // 預設10個物件空間 } public SimpleCollection(int capacity) { objArr = new Object[capacity]; } public void add(T t) { objArr[index] = t; index++; } public int getLength() { return index; } public T get(int i) { return (T) objArr[i]; } }
如果您已經定義了一個泛型類別,想要用這個類別來於另一個泛型類別中宣告成員的話要如何作?舉個實例,假設您已經定義了下面的類別:
public class GenericFoo<T> { private T foo; public void setFoo(T foo) { this.foo = foo; } public T getFoo() { return foo; } }
您想要寫一個包裝類別(Wrapper),這個類別必須也具有GenericFoo的泛型功能,您可以這麼寫:
public class WrapperFoo<T> { private GenericFoo<T> foo; public void setFoo(GenericFoo<T> foo) { this.foo = foo; } public GenericFoo<T> getFoo() { return foo; } }
這麼一來,您就可以保留型態持有者 T 的功能,一個使用的例子如下:
GenericFoo<Integer> foo = new GenericFoo<Integer>();
foo.setFoo(new Integer(10));
WrapperFoo<Integer> wrapper = new WrapperFoo<Integer>();
wrapper.setFoo(foo);
|