参考 http://tutorials.jenkov.com/java-generics/methods.html
定义使用泛型的类
public class GenericFactory<E> {
Class theClass = null;
public GenericFactory(Class aClass){
this.theClass = aClass;
}
public E createInstance() throws IllegalAccessException, InstantiationException {
return (E)theClass.newInstance();
}
}
定义使用泛型的方法
private static <T> T addAndReturn(T element,Collection<T> collection){
collection.add(element);
return element;
}
在类声明和方法声明时,用<T>(<>中字符任意)声明一个“泛型类型”
private static <T> T getInstance(Class<T> aClass) throws IllegalAccessException, InstantiationException {
return aClass.newInstance();
}
泛型通配符(wildcards)
List<?> listUknown = new ArrayList<A>(); List<? extends A> listUknown = new ArrayList<A>(); List<? super A> listUknown = new ArrayList<A>();
List<?>
means a list typed to an unknown type.
List<? extends A>
means a List
of objects that are instances of the class A, or subclasses of A (e.g. B and C).
List<? super A>
means that the list is typed to either the A class, or a superclass of A.
public void processElements(List<?> elements){
for(Object obj : elements){
//do something
}
}
public void processElements(List<? extends A> elements){
for(A a : elements){
System.out.println(a.getValue());
}
}
public void processElements(List<? super A> elements){
for(Object a : elements){
//do something
}
}
为什么使用泛型?
1,不需要类型强转,因为编译器已做过类型检查
2,使用泛型后,对Collection就可以使用for-each循环了。