What is "T ..." in Java?

Looking at the methods of the Array class on libgdx . I found this method:

public void addAll (T... array) { addAll(array, 0, array.length); } 

I have never seen this “T ...” before, and it turns out that it is incredibly difficult to find “T ...” either on Google or here on Stack Overflow. I think I understand generics, but "..." is new to me.

What does it mean? So, for example, if T is a String, then how will I use this method? Why should I use this? And how will this differ from using "T []" instead?

+7
java syntax generics libgdx
source share
2 answers

T... is just a varargs parameter, where the element type is T , the generic type of the class type.

The thing is, you can call a method like this (if array is Array<String> ):

 array.addAll("x", "y", "z"); 

which will be equivalent

 array.addAll(new String[] { "x", "y", "z" }); 

It can be used without generics. For example:

 public static int sum(int... elements) { int total = 0; for (int element : elements) { total += element; } return total; } 

Varargs parameters were introduced in Java 5.

+24
source share

There are two things here:

First, it is probably a class that uses Generics , so T is a parameterized type.

Secondly, the declaration of the parameter T... represents varargs

+7
source share

All Articles