Lucas
Lucas

Reputation: 3281

A little confusion around generics

I started reading some article about generics in Java and one thing confused me:

public static <t> T getFirst(List<T> list)

"This method will accept a reference to a List and will return an object of type T."

cool, but what does <t> do (the lower case one, after static)? I tried and failed to understand it...

Upvotes: 2

Views: 62

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

It should rather be :

public static <T> T getFirst(List<T> list)
  • So, what does the <T> mean ?

    It means that there is a type called <T> for the scope of this method. And the method will return an instance of that type T, also.

  • How to use it ?

    If you pass a List<String> the method should return the first String in the list.

    If you pass a List<Integer> the method should return the first Integer in the list.

  • What's the point of supporting such methods ?

    • You don't have to overload methods with different signatures, according to the type of the objects in the List and

    • You don't have to worry that the method will return other type than the type of the objects in the list, which will relief you from the burden of possible casting, for example.

Upvotes: 6

user2424380
user2424380

Reputation: 1473

Maybe it is more understandable like this:

public static <T> T getFirst(T something)

In short means that the type T will be a parameter given later when you call the method:

String text = "text";
getfirst(text);

Now the compiler will know that all the T means String here.

Upvotes: 1

Related Questions