Friday 9 August 2019

variadic functions - Java, 3 dots in parameters



What do the 3 dots in the following method mean?



public void myMethod(String... strings){
// method body
}

Answer



It means that zero or more String objects (or an 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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...