java 中函数参数个数未知的两种实现形式
//:initialization/VarArgs.java
class A {}
public class VarArgs
{
static void printArray(Object[] args) {
for (Object obj : args)
System.out.print(obj +" ");
System.out.println();
}
public static void main(String[] args) {
printArray(new Object[] {
new Integer(47),
new Float(3.14),
new Double(11.11)
});
printArray(new Object[] {"one","two","three"});
printArray(new Object[] {new A(),new A(),new A()});
}
}
/*output:
47 3.14 11.11
one two three
A@1a46e30 A@3e25a5 A@19821f
*/
以上是JavaSE5以前的做法,下边的是JavaSE5中新增的特性,更加方便使用
//:initialization/NewVarArgs.java
public class NewVarArgs {
static void printArray(Object... args) {
for(Object obj : args)
System.out.print(obj + " ");
System.out.println();
}
public static void main(String[] args) {
printArray(new Integer(47),
new Float(3.14),
new Double(11.11));
printArray(47,3.14F,11,11);
printArray("one","two","three");
printArray(new A(),new A(),new A());
//or an array
printArray((Object[])new Integer[] {1,2,3,4});
printArray();//Empty list is OK
}
}
/*output
47 3.14 11.11
47 3.14 11 11
one two three
A@1a46e30 A@3e25a5 A@19821f
1 2 3 4
*/
此篇文章为阅读Thinking in Java摘抄
没有评论:
发表评论