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.
Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.
A generic class and a generic method can handle any type of data.
Both ArrayList and vector are generic types. But the C++ vector template overloads the [] operator for convenient element access.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With