June 29, 2012

Java Varargs - Unlimited parameters to a Java method

When you cannot decide the number of parameters you need for a method, varargs becomes the solution. Earlier, if we couldn't determine such, we had to use a collection as a parameter to help with this scenario. But varargs simplifies this.

Varargs does use an array underneath, but using varargs syntax hides the process.

public static String format(String pattern,
                                Object... arguments);

Example :

If you need to write a file name extension filter for a number of extensions, you can use this method of defining the method.

public FileNameExtensionFilter(String description, String... extensions) {

Read more on varargs at :
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

No comments:

Post a Comment