What does the 3 dots in the following function mean?
function x(String... strings)
{
//
}
What does the 3 dots in the following function mean?
function x(String... strings)
{
//
}
That feature is called varargs, and it's a feature introduced in Java 5. It means that function can receive multiple String
arguments:
x("foo", "bar");
x("foo", "bar", "baz");
x(new String[]{"foo", "var", "baz"}); // you can even pass an array
Then, you can use the String
var as an array:
function x(String... strings){
for(String whatever : strings){
// do what ever you want
}
// the code above is is equivalent to
for( int i = 0; i < strings.length; i++){
// classical for. In this case you use strings[i]
}
}
This answer borrows heavily from kiswa's and Lorenzo's... and also from the Graphain's comment.
It means that zero or more String objects (or an array of them) may be passed as the parameter(s) for that function.
See the "Arbitrary Number of Arguments" section here: http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html#varargs
In your example, you could call it as any of the following:
x(); // Likely useless, but possible
x("one", "two", "three");
x("solo");
x(new String[]{"a", "b", "c"});
Important Note: The parameter(s) passed in this way is always an array - even if there's just one. Make sure you treat it that way in the method body.
Important Note 2: The parameter that gets the ... must be the last in the method signature. So, x(int i, String... strings)
is okay, but x(String... strings, int i)
is not okay.
Thanks to Vash for the clarifications in his comment.
This is the Java way to pass varargs (variable number arguments).
If you are familiar with C, this is similar to the ...
syntax used it the printf
function:
int printf(const char * format, ...);
but in a type safe fashion: every argument has to comply with the specified type (in your sample, they should be all String
).
This is a simple sample of how you can use varargs:
class VarargSample {
public static void PrintMultipleStrings(String... strings) {
for( String s : strings ) {
System.out.println(s);
}
}
public static void main(String... args) {
PrintMultipleStrings("Hello", "world");
}
}
The ...
argument is actually an array, so you could pass a String[]
as the parameter.