以object数组为参数的方法实现可变参数列表
package chapter5; /**
* 以object数组为参数的方法实现可变参数列表
*/
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(55), new Float(5.34),
new Double(3.56) });
printArray(new Object[] { "one", "two", "three" });
printArray(new Object[] { new A(), new A(), new A() });
}
}
【运行结果】:
55 5.34 3.56
one two three
chapter5.A@18a992f chapter5.A@4f1d0d chapter5.A@1fc4bec
java SE5之后,有了新特性可以实现可变参数列表
package chapter5; /**
* 可变参数列表
*/
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(33), new Float(5.23), new Double(3.55));
printArray(33,5.23f,3.55d);
printArray("one","two","three");
printArray(new A(),new A(),new A());
printArray((Object[])new Integer[]{1,2,3,4,5,6});
printArray();
} }
【运行结果】:
33 5.23 3.55
33 5.23 3.55
one two three
chapter5.A@18a992f chapter5.A@4f1d0d chapter5.A@1fc4bec
1 2 3 4 5 6
上面的例子中,printArray();是正确的,表明可以将0个参数传递给可变参数列表。当具有可选的尾随参数是,很有用。
package chapter5; /**
* 有可选尾随可变参数列表
*/
public class OptionalTrailingArguments {
static void f(int required, String... trailing) {
System.out.print("required:" + required + " ");
for (String s : trailing)
System.out.print(s + " ");
System.out.println();
} public static void main(String[] args) {
f(1, "one");
f(2, "one", "two");
f(0);
}
}
【运行结果】:
required:1 one
required:2 one two
required:0
可变参数列表与自动包装机制和谐共处
package chapter5; /**
* 可变参数列表与自动包装机制和谐共处
*/
public class AutoboxingVarargs {
static void f(Integer... args) {
for (Integer i : args)
System.out.print(i + " ");
System.out.println();
} public static void main(String[] args) {
f(new Integer(1), new Integer(2));
f(4, 5, 6, 7);
f(23, new Integer(24), 25);
}
}
【运行结果】:
1 2
4 5 6 7
23 24 25
可变参数列表使重载变复杂
package chapter5; /**
* 可变参数列表使重载变复杂
*/
public class OverloadVargs { static void f(Character... args) {
System.out.print("first");
for (Character c : args)
System.out.print(" " + c);
System.out.println();
} static void f(Integer... args) {
System.out.print("second");
for (Integer i : args)
System.out.print(" " + i);
System.out.println();
} static void f(Long... args) {
System.out.print("Third");
} public static void main(String[] args) {
f('a','b','c');
f(1);
f(2,1);
f(0);
f(0L);
//f();
} }
【运行结果】:
first a b c
second 1
second 2 1
second 0
Third
上例会自动匹配重载的方法,但是调用f()时,就不知道匹配哪个方法了,此时须增加一个可变参数来解决问题。