- 简单的泛型定义使用:
public class GenericFoo<T> { private T foo; public void setFoo(T foo){ this.foo = foo; } public T getFoo(){ return this.foo; } public static void main(String[] args){ //GenericFoo is a raw type, References to generic type GenericFoo<T> should be parameterized. GenericFoo foo = new GenericFoo(); GenericFoo<String> sFoo = new GenericFoo<String>(); GenericFoo<Integer> iFoo = new GenericFoo<Integer>(); sFoo.setFoo("string foo"); // sFoo.setFoo(11); //这里只能放置String类型的,放置11在编译时就会报错。 iFoo.setFoo(11); } }
2.定义两个泛型,以及泛型数组的定义使用:
public class GenericFoo2<T,E> { private T foo1; private E foo2; private T[] arrays; public T getFoo1() { return foo1; } public void setFoo1(T foo1) { this.foo1 = foo1; } public E getFoo2() { return foo2; } public void setFoo2(E foo2) { this.foo2 = foo2; } public T[] getArrays() { return arrays; } public void setArrays(T[] arrays) { this.arrays = arrays; } public static void main(String[] args){ GenericFoo2<String,Boolean> gf = new GenericFoo2<String,Boolean>(); gf.setFoo1("string"); gf.setFoo2(false); gf.setArrays(new String[]{"aa","bb"}); } }
3.模仿ArrayList实现集合泛型化:
public class GenericCollection<E> { private Object[] array; private int index; public GenericCollection(){ this(10); } public GenericCollection(int capacity){ array = new Object[capacity]; } public void add(E e){ array[index++] = e; } public E get(int index){ return (E)array[index]; } public static void main(String[] args){ GenericCollection<Integer> gc = new GenericCollection<Integer>(); for(int i=0;i<10;i++){ gc.add(i*2); } for(int i=0;i<10;i++){ System.out.println(gc.get(i)); } } }
时间: 2024-10-24 00:58:56