我想知道只有当方法是静态时才使用泛型方法吗?对于非静态的你可以定义一个泛型类,你不需要它是通用的方法。那是对的吗 ?Java:泛型方法只与静态?
例如,
public class Example<E>{
//this is suffice with no compiler error
public void doSomething(E [] arr){
for(E item : arr){
System.out.println(item);
}
}
//this wouldn't be wrong, but is it necessary ?
public <E> doSomething(E [] arr){
for(E item : arr){
System.out.println(item);
}
}
}
,而编译器将强制添加类型参数,使其成为通用的方法,如果它是静态的。
public static <E> doSomething(E [] arr){
}
我不知道我是否正确。
你也可以拥有通用的实例方法,而不需要使你的类成为通用的。 – 2012-08-09 14:17:19