我想知道只有當方法是靜態時才使用泛型方法嗎?對於非靜態的你可以定義一個泛型類,你不需要它是通用的方法。那是對的嗎 ?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