Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "<T> T get()" mean? (And is it useful?)

Tags:

java

generics

This seems to be valid Java syntax:

<T> T get();

But what does it mean? And is it useful?


CLARIFICATION FOR DOWNVOTERS

I understand what it means when the T is used in the method parameters, like this:

T get(Class<T> clazz);

The return type is inferrable from the class that's passed in.

But when you have no parameters to say what type T is, what type is it?

like image 288
ᴇʟᴇvᴀтᴇ Avatar asked Apr 01 '16 18:04

ᴇʟᴇvᴀтᴇ


1 Answers

It is the type of the variable you are assigning the return-value to.

e.g. If you have a method like this one:

public static <T> T getGenericNumber() {
    // the number-generator might return int, double, float etc. values
    return (T) numberGenerator.getANumber();
}

You can for instance assign the return value of the method directly to a double value - without a cast:

Double a = getGenericNumber();

So you have basically moved your cast from the declaration of the variable into the method.

This is potentially dangerous because you can easily produce cast-exceptions cause you could do things like this - and still being able to compile:

String s = getGenericNumber();
like image 163
Kristian Ferkić Avatar answered Nov 15 '22 18:11

Kristian Ferkić