Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Is generic method only with static?

Tags:

java

generics

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.

like image 686
peter Avatar asked Aug 09 '12 14:08

peter


People also ask

Can you have a generic method in a non generic class?

Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.

Can generic class handle any type of data?

A generic class and a generic method can handle any type of data.

Can ArrayList be generic?

Both ArrayList and vector are generic types. But the C++ vector template overloads the [] operator for convenient element access.

Can generic types be inherited Java?

Generics also provide type safety (ensuring that an operation is being performed on the right type of data before executing that operation). Hierarchical classifications are allowed by Inheritance. Superclass is a class that is inherited. The subclass is a class that does inherit.


1 Answers

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.
like image 177
Peter Lawrey Avatar answered Oct 08 '22 22:10

Peter Lawrey