Java: is the general method only static?

I wonder if we use the general method only if the method is static? for non-static, you define a generic class, and you don't need it to be a universal method. It is right?

eg,

  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);
                }
         }
  }

whereas the compiler will force you to add a type parameter to make it universal if it is static.

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


  }

I'm not sure if I'm right or not.

+5
source share
3 answers
public class Example<E>{

defines a generic type for instance methods and fields.

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

This defines a second Ethat is different from the first and can be confusing.

Note: voidstill required;)

Static fields and methods do not use common class types.

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

private static final List<E> list = new ArrayList<>(); // will not compile.
+4
source

, Example<String> example = new Example<String>();.

  • public void doSomething(E [] arr) String[]
  • public <E> void doSomething(E [] arr) ( E, Example<E>)
  • public static <E> void doSomething(E [] arr)

, Example<E> , E , . . .

+3

Consider the interface java.util.Collection. It is declared as:

public interface Collection<E>{
  //...
  <T> T[] toArray(T[] a);
}

toArrayis a generic instance method using a type parameter Tthat has nothing to do with the type parameter Efrom the interface declaration.

This is a good example from the JDK itself, which illustrates the importance of having common instance methods.

0
source

All Articles