Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Type of Java Generic Methods

People also ask

Can you return a generic Java?

(Yes, this is legal code; see Java Generics: Generic type defined as return type only.) The return type will be inferred from the caller. However, note the @SuppressWarnings annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions at runtime.

How do you return a type in Java?

Returning a Value from a Method In Java, every method is declared with a return type such as int, float, double, string, etc. These return types required a return statement at the end of the method. A return keyword is used for returning the resulted value. The void return type doesn't require any return statement.

What is generic method in Java?

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.


This question suits one of my old notes. I hope this illustration helps:

enter image description hereenter image description here


The <E> is the generic type parameter declaration. It means "this method has a single type parameter, called E, which can be any type".

It's not the return type - that comes after the type parameter declaration, just before the method name. So the return type of the printArray method in your question is still void.

See section 8.4 of the JLS for more details about method declarations.


It's not the type of the returned object. It indicates that E, in the method signature, is a generic type and not a concrete type. Without it, the compiler would look for a class named E for the argument of the method.


The < E > is called a formal type parameter. It is not the return type of the method. It basically says that the method can accept as parameters arrays of different types (E[] inputArray).


E is used as a placeholder for the actual type that will be passed to Gen function when this function will call.

suppose E can be replaced by integer