maček maček - 5 months ago 14
Java Question

How to create Java method that accepts variable number of arguments?

For example, Java's own

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?


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(player2, player3, player4);

// 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.