mač*_*ček 67 java methods overloading function
例如,Java自己String.format()
支持可变数量的参数.
String.format("Hello %s! ABC %d!", "World", 123);
//=> Hello World! ABC 123!
Run Code Online (Sandbox Code Playgroud)
如何创建自己接受可变数量参数的函数?
后续问题:
我真的想为此做一个方便的捷径:
System.out.println( String.format("...", a, b, c) );
Run Code Online (Sandbox Code Playgroud)
所以我可以把它称为不那么冗长的东西:
print("...", a, b, c);
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
Nat*_* W. 112
你可以写一个方便的方法:
public PrintStream print(String format, Object... arguments) {
return System.out.format(format, arguments);
}
Run Code Online (Sandbox Code Playgroud)
但正如您所看到的,您只需重命名format
(或printf
).
以下是您可以使用它的方法:
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
Run Code Online (Sandbox Code Playgroud)
请注意,也有类似的System.out.printf
方法,行为方式相同,但如果您查看实现,printf
只需调用format
,所以您也可以format
直接使用.
PrintStream#format(String format, Object... args)
PrintStream#printf(String format, Object... args)
Pau*_*lan 26
这被称为varargs,请点击此处链接了解更多详情
在过去的Java版本中,采用任意数量值的方法需要您创建数组并在调用方法之前将值放入数组中.例如,以下是使用MessageFormat类格式化消息的方式:
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);
Run Code Online (Sandbox Code Playgroud)
仍然需要在数组中传递多个参数,但varargs功能会自动化并隐藏进程.此外,它与先前存在的API向上兼容.因此,例如,MessageFormat.format方法现在具有此声明:
public static String format(String pattern,
Object... arguments);
Run Code Online (Sandbox Code Playgroud)
看看varargs上的Java指南.
您可以创建如下所示的方法.只需致电System.out.printf
而不是System.out.println(String.format(...
.
public static void print(String format, Object... args) {
System.out.printf(format, args);
}
Run Code Online (Sandbox Code Playgroud)
或者,如果要尽可能少地键入,则可以使用静态导入.那么你不必创建自己的方法:
import static java.lang.System.out;
out.printf("Numer of apples: %d", 10);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
184194 次 |
最近记录: |