Common functions in Java

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

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

      

Can someone explain what this means succinctly?
Does this mean that foo () takes in an array of type T and returns type T?
Why not the syntax shown below?

public static T foo(T[] a)

      

I have looked at the Oracle docs, but an example they seem to be much easier to understand: Oracle Generics

+3


source to share


3 answers


Two things:

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

You call this method like foo(a,b,c)

(as opposed to foo(arrayWithABC)

).

2) If you want to use a generic type placeholder T

, you must declare it. This is exactly what the first one does <T>

.



The difference between public static T foo(T a)

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

is that the latter introduced "local" T

for the scope of this method. This means that "the method returns an instance of any type parameter a

". In the first version, it T

must be a type placeholder declared elsewhere (for example, for the class as a whole) or the name of the class.

Since it is <T>

completely unlimited, you can transfer whatever you want. What generics do is associate the return value with the same type. If yours only public static Object foo(Object a)

, you can transfer Integer

and return String

. T

prevents this.

If you want to restrict the allowed types, you can do public static <T extends Number> T foo(T a)

.

+7


source


T... a 

      

means a variable number of object arguments of type T for a method, whereas



T[] a

      

means one argument of an array of T objects

0


source


This means that type "T" will match any real type. Its like a wild card type :)

0


source







All Articles