Friday, August 9, 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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...