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;
}
(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.
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.
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.
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.
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 Vector
s).
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