peter
peter

Reputation: 8473

Java : Is generic method only with static?

I am wondering do we use generic method only if the method is static ? for non-static you would define a generic class and you don't necessary need it to be generic method. Is that correct ?

for example,

  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 to add type parameter to make it a generic method if it's static.

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


  }

I am not sure if i am correct or not.

Upvotes: 6

Views: 1831

Answers (3)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78649

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

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

The toArray is a generic instance method using a type parameter T, which has no relation whatsoever with the type parameter E from the interface declaration.

This a good example from the JDK itself that illustrates the value of having generic instance methods.

Upvotes: 1

assylias
assylias

Reputation: 328913

Let's say you declare an Example<String> example = new Example<String>();.

  • public void doSomething(E [] arr) will expect a String[] argument
  • public <E> void doSomething(E [] arr) will expect an array of any type (it's not the same E as in Example<E>)
  • public static <E> void doSomething(E [] arr) will expect an array of any type

In any case, since your Example<E> can be parameterized, you can't use that E in a static call as it will be instance dependent. It would be a bit like calling a non static member from a static method. So you have to redefine it locally.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533880

public class Example<E>{

defines a generic type for instance's methods and fields.

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

This defines a second E which is different to the first and is likely to be confusing.

Note: void is still needed ;)

Static fields and methods do not use the generic types of the class.

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

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

Upvotes: 4

Related Questions