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.
defines a generic type for instance’s methods and fields.
This defines a second
Ewhich is different to the first and is likely to be confusing.Note:
voidis still needed 😉Static fields and methods do not use the generic types of the class.