Browsing through Guava libraries I saw this weird signature on the readLines method of the Files class:
public static <T> T readLines(File file,
Charset charset,
LineProcessor<T> callback)
I know a little bit about generics in Java, but this baffled me.
What does the double T mean here? And why is the first one in angled brackets?
After some answers, I am still not clear as to why I should use a T inside the brackets. Why for example can’t it just be:
public static <> T readLines()
or
public static <K> T readLines()
Or does the Java syntax dictate that the same letter must be used?
Now this is even wierder:
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
how can a method have a generic-return type and be void?
The
<T>or<K>is the type parameter. If you write<K> T, then the T isn’t a type parameter – rather, you’re using the specificclass T. This won’t work if you don’t have a class that’s literally namedTin scope.It doesn’t; the
<T>is not a “generic return type”, it’s just the type parameter to the method. You’re saying that the method is generic, andTis the type parameter. The return type of the method isvoid.