Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java weird generic return type

Tags:

java

generics

Browsing through Guava libraries I saw this weird signature on a readLines method from 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?

UPDATE: Thanks for the 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

 pulibc 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?

like image 969
Andriy Drozdyuk Avatar asked May 20 '10 19:05

Andriy Drozdyuk


2 Answers

It's a generic method -- the T is called a type parameter, and can represent any type. So if I have a method with this signature:

public <T> T foo(T[] bar)

I can call it on any array, and it will return a single object of the same type. If I pass it a String array, I'll get back a String, and so on. More information in the Sun tutorials for "generic methods".

Edit: In answer to your updated question, bear in mind that the first <T> isn't part of the return type: it's just an indicator that T is a type parameter. So look at the example you quoted:

static <T> void fromArrayToCollection(T[] a, Collection<T> c)

That just means that fromArrayToCollection will accept any array and any collection, but that they must be an array and collection of the same type. So you can pass in a String[] and a Collection<String>, or an Integer[] and a Collection<Integer>, but not a String[] and a Collection<Integer>. No matter what type you put in for T, the method returns nothing.

like image 51
Etaoin Avatar answered Sep 30 '22 05:09

Etaoin


The first T inside the angle brackets mean that the method itself is generic. The second T is the return type. T can be any type within its bounds. In this case, T has no bounds.

T will be determined at the call site, and in this case, inferred from the LineProcessor<T> parameter.

like image 21
ILMTitan Avatar answered Sep 30 '22 06:09

ILMTitan