Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Generic method and return type

Tags:

java

generics

Can anyone explain what does the return type mean in the following code

public static <T> ArrayList<T> a()
{       
       return null;
} 

and

public static <String> ArrayList<Vector> a()
{       
       return null;
} 
like image 672
peter Avatar asked Aug 08 '12 19:08

peter


People also ask

How do I return a generic class type in 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.

How does a generic method differ from a generic type?

From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.

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.


1 Answers

public static <T> ArrayList<T> a() 

The first occurance of <T> introduces a type parameter which will be available within the method.

The actual return type is ArrayList<T>, where T is same as the one in the first.

You can read about it here - Generic Methods.

In the second one:

public static <String> ArrayList<Vector> a() {

Even though you have introduced a generic type parameter (i.e. String, which is not an actual type or argument like java.lang.String) you are not using it. And, also the method always returns an ArrayList<Vector> (ArrayList of Vectors).

like image 111
Bhesh Gurung Avatar answered Oct 10 '22 21:10

Bhesh Gurung