Java:只有静态的泛型方法吗?

pet*_*ter 5 java generics

我想知道我们只有在方法是静态的时候才使用泛型方法吗?对于非静态的,您将定义一个泛型类,并且您不必将它作为泛型方法.那是对的吗 ?

例如,

  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);
                }
         }
  }
Run Code Online (Sandbox Code Playgroud)

而编译器将强制添加类型参数,使其成为通用方法,如果它是静态的.

  public static <E> doSomething(E [] arr){


  }
Run Code Online (Sandbox Code Playgroud)

我不确定我是否正确.

Pet*_*rey 4

public class Example<E>{
Run Code Online (Sandbox Code Playgroud)

为实例的方法和字段定义通用类型。

public void <E> doSomething(E [] arr){
Run Code Online (Sandbox Code Playgroud)

这定义了第二个E与第一个不同的并且可能会令人困惑。

注意:void仍然需要;)

静态字段和方法不使用类的泛型类型。

public static <F> doSomething(F [] arr) { }

private static final List<E> list = new ArrayList<>(); // will not compile.
Run Code Online (Sandbox Code Playgroud)