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

193,473

Solution 1

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.

Solution 2

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);

Solution 3

Take a look at the Java guide on varargs.

You can create a method as shown below. Simply call System.out.printf instead of System.out.println(String.format(....

public static void print(String format, Object... args) {
    System.out.printf(format, args);
}

Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:

import static java.lang.System.out;

out.printf("Numer of apples: %d", 10);

Solution 4

This is just an extension to above provided answers.

  1. There can be only one variable argument in the method.
  2. Variable argument (varargs) must be the last argument.

Clearly explained here and rules to follow to use Variable Argument.

Solution 5

The following will create a variable length set of arguments of the type of string:

print(String arg1, String... arg2)

You can then refer to arg2 as an array of Strings. This is a new feature in Java 5.

Share:
193,473
maček
Author by

maček

Updated on November 30, 2020

Comments

  • maček
    maček over 3 years

    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?

  • maček
    maček over 12 years
    So this has already been implemented? Should I just use it as PrintStream.print("...", a, b, c)? Provide a usage example and I will mark this as accepted answer :)
  • Nate W.
    Nate W. over 12 years
    Yep, this is already provided on PrintStream, which System.out happens to be :D You can use either printf or format
  • Malwinder Singh
    Malwinder Singh almost 9 years
    @NateW. How does it differs from private void printScores(Player[] players) {}?
  • Nate W.
    Nate W. almost 9 years
    @M.S. In your example, the only valid argument to the method would be an array. On the other hand, with a vararg parameter, an array, a single element, and multiple comma-separated elements are all valid. There are more ways to call it.