-- Start
我们先看一个例子.
public class Test {
public static void main(String[] args) throws Exception {
print(new String[] { "a", "b" });
}
public static void print(String[] strs) {
for (String str : strs) {
System.out.print(str);
}
}
}
在 JDK 1.5 之前, 当一个方法参数类型确定而参数个数不确定时, 我们可以定义该方法接受一个数组类型的参数. 从 JDK 1.5 开始, 我们不必这么麻烦了, 我们可以定义该方法接受可变参数, 如下:
public class Test {
public static void main(String[] args) throws Exception {
print();
print("a");
print("a", "b");
}
public static void print(String... strs) {
for (String str : strs) {
System.out.print(str);
}
}
}
可以看到, 我们可以给 print 方法传递任意数量的参数. 值得注意的是, 一个方法只接受一个可变参数且它必须位于最后一项。因为参数个数不定,所以当其后边还有相同类型参数时,java无法区分传入的参数属于前一个可变参数还是后边的参数,所以只能让可变参数位于最后一项.
---更多参见:Java 精萃
-- 声 明:转载请注明出处
-- Last Updated on 2012-06-12
-- Written by ShangBo on 2012-06-12
-- End