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 had never seen that "T..." before, and it turns out that it's incredibly hard to search for "T..." either on Google or here on Stack Overflow. I think I understand generics, but the "..." is new to me.
What does that mean? So, for example, if T is String, then how would I use this method? Why would I use it? And how would that be different from using "T[]" instead?
The T...
is just a varargs parameter, where the element type happens to be T
, the generic type parameter of the class.
The point is that you can call the method like this (assuming array
is an Array<String>
):
array.addAll("x", "y", "z");
which will be equivalent to
array.addAll(new String[] { "x", "y", "z" });
This can be used without generics too. 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.
See more on this question at Stackoverflow