Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic functions in Java

Tags:

java

generics

I am not very familiar with some of the generic syntax in Java.
I came across some code like this:

public static<T> T foo(T... a)

Can somebody explain what it means in a succinct way?
Does it mean foo() takes in an array of type T and returns type T?
Why isn't the syntax like this below?

public static T foo(T[] a)

I had a look at the Oracle docs but the example they have seems much easier to understand: Oracle Generics

like image 461
user2399453 Avatar asked Nov 28 '25 01:11

user2399453


1 Answers

Two things:

1) This is a varargs method, a method that takes a variable number of arguments. That is not the same as a method that takes an array (even though under the hoods it is implemented using an array).

You call this method as foo(a,b,c) (as opposed to foo(arrayWithABC)).

2) If you want to use the generic type placeholder T, you have to declare it. This is exactly what the first <T> does.

The difference between public static T foo(T a) and public static <T> T foo(T a) is that the latter introduced a "local" T for the scope of this method. That means "method returns an instance of whatever type parameter a has". In the first version, the T would need to be a type placeholder declared elsewhere (such as on the class as a whole), or a class name.

Since <T> is completely unrestricted you can pass anything. What the generics do is bind the return value to the same type. If you just had public static Object foo(Object a), you could pass in an Integer and get back a String. The T prevents that.

If you wanted to restrict the acceptable types, you could do public static <T extends Number> T foo(T a).

like image 187
Thilo Avatar answered Nov 29 '25 13:11

Thilo