Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a Java method that accepts a variable number of arguments?

For example, Java's own String.format() supports a variable number of arguments.

String.format("Hello %s! ABC %d!", "World", 123); //=> Hello World! ABC 123! 

How can I make my own function that accepts a variable number of arguments?


Follow-up question:

I'm really trying to make a convenience shortcut for this:

System.out.println( String.format("...", a, b, c) ); 

So that I can call it as something less verbose like this:

print("...", a, b, c); 

How can I achieve this?

like image 764
maček Avatar asked Sep 30 '11 07:09

maček


People also ask

What type of methods takes a variable number of arguments?

This argument that can accept variable number of values is called varargs. In order to define vararg, ... (three dots) is used in the formal parameter of a method. A method that takes variable number of arguments is called a variable-arity method, or simply a varargs method.

How do you accept multiple arguments in Java?

Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

What are the valid method declaration with variable number of arguments in Java?

Hence, in the Varargs method, we can differentiate arguments by using Index. A variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].


2 Answers

You could write a convenience method:

public PrintStream print(String format, Object... arguments) {     return System.out.format(format, arguments); } 

But as you can see, you've simply just renamed format (or printf).

Here's how you could use it:

private void printScores(Player... players) {     for (int i = 0; i < players.length; ++i) {         Player player = players[i];         String name   = player.getName();         int    score  = player.getScore();         // Print name and score followed by a newline         System.out.format("%s: %d%n", name, score);     } }  // Print a single player, 3 players, and all players printScores(player1); System.out.println(); printScores(player2, player3, player4); System.out.println(); printScores(playersArray);  // Output Abe: 11  Bob: 22 Cal: 33 Dan: 44  Abe: 11 Bob: 22 Cal: 33 Dan: 44 

Note there's also the similar System.out.printf method that behaves the same way, but if you peek at the implementation, printf just calls format, so you might as well use format directly.

  • Varargs
  • PrintStream#format(String format, Object... args)
  • PrintStream#printf(String format, Object... args)
like image 94
Nate W. Avatar answered Oct 11 '22 15:10

Nate W.


This is known as varargs see the link here for more details

In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:

Object[] arguments = {     new Integer(7),     new Date(),     "a disturbance in the Force" };     String result = MessageFormat.format(         "At {1,time} on {1,date}, there was {2} on planet "          + "{0,number,integer}.", arguments); 

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:

public static String format(String pattern,                             Object... arguments); 
like image 35
Paul Whelan Avatar answered Oct 11 '22 16:10

Paul Whelan