如何创建接受可变数量参数的 Java 方法? [英] How can I create a Java method that accepts a variable number of arguments?
问题描述
例如,Java 自己的 String.format()
支持可变数量的参数.
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?
后续问题:
我真的想为此创建一个方便的快捷方式:
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);
}
但是正如你所看到的,你只是简单地重命名了format
(或printf
).
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
请注意,还有类似的 System.out.printf
方法,其行为方式相同,但如果您查看实现,printf
只会调用 format
,所以你也可以直接使用format
.
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.
- 可变参数
PrintStream#format(String format, Object... args)
PrintStream#printf(String format, Object... args)
这篇关于如何创建接受可变数量参数的 Java 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!