General functions in Java

I'm not familiar with some general syntax in Java

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

Can anyone explain its meaning in a concise way? Does this mean that foo () accepts an array of type T and returns type T? Why not such grammar?

public static T foo(T[] a)

I looked at the Oracle documentation, but their example seems easier to understand: Oracle generics

Solution

Two things:

1) This is a varargs method, a method that takes a variable number of parameters This is different from using arrays (even under the hood)

You call this method foo (a, B, c) (as opposed to foo (arraywithabc)

2) If you want to use generic type placeholder T, you must declare it This is the first < T > indeed

Difference between common static t foo (TA) and common static < T > T foo (TA) is the latter, which introduces "local" t for the scope of the method, which means that "the method returns an instance of any type of parameter" In the first version, t needs to be a type placeholder declared elsewhere (for example, as a whole in a class) or a class name

Since < T > is completely unrestricted, you can pass anything The function of generics is to bind the return value to the same type If you only have public static object foo (object a), you can pass in an integer and return a string T stopped this

If you want to limit the acceptable types, you can do public static < T extends number > t foo (t a)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>