What do the 3 dots following String
in the following method mean?
public void myMethod(String... strings){
// method body
}
A really common way to see a clear example of the use of the three dots it is present in one of the most famous methods in android AsyncTask ( that today is not used too much because of RXJAVA, not to mention the Google Architecture components), you can find thousands of examples searching for this term, and the best way to understand and never forget anymore the meaning of the three dots is that they express a ...doubt... just like in the common language. Namely it is not clear the number of parameters that have to be passed, could be 0, could be 1 could be more( an array)...
Just think of it as the keyword params
in C#, if you are coming from that background :)
That feature is called varargs, and it's a feature introduced in Java 5. It means that function can receive multiple String
arguments:
myMethod("foo", "bar");
myMethod("foo", "bar", "baz");
myMethod(new String[]{"foo", "var", "baz"}); // you can even pass an array
Then, you can use the String
var as an array:
public void myMethod(String... strings){
for(String whatever : strings){
// do what ever you want
}
// the code above 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 Graphain's comment.
Adding to the other well-written answers, an advantage of varagrs
I found useful is that, when I call a method with array as a parameter type, it takes away the pain of creating an array; add elements and then send it. Instead, I can just call the method with as many values as I want; from zero to many.
String...
is the same as String[]
import java.lang.*;
public class MyClassTest {
//public static void main(String... args) {
public static void main(String[] args) {
for(String str: args) {
System.out.println(str);
}
}
}
It means that zero or more String objects (or a single array of them) may be passed as the argument(s) for that method.
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:
myMethod(); // Likely useless, but possible
myMethod("one", "two", "three");
myMethod("solo");
myMethod(new String[]{"a", "b", "c"});
Important Note: The argument(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 argument that gets the ...
must be the last in the method signature. So, myMethod(int i, String... strings)
is okay, but myMethod(String... strings, int i)
is not okay.
Thanks to Vash for the clarifications in his comment.