在Java5 中提供了变长参数(varargs),也是在方法定义中可以使用个数不确定的参数,对于同一方法可以使用不同个数的参数调用,例如print("hello");print("hello","lisi");print("hello","张三", "alexia");下面介绍如何定义可变长参数 以及如何使用可变长参数。

  1. 可变长参数的定义

  使用...表示可变长参数,例如

print(String... args){
...
}

  在具有可变长参数的方法中可以把参数当成数组使用,例如可以循环输出所有的参数值。

print(String... args){
   for(String temp:args)
      System.out.println(temp);
}

  2. 可变长参数的方法的调用

  调用的时候可以给出任意多个参数也可不给参数,例如:

print();
print("hello");
print("hello","lisi");
print("hello","张三", "alexia")

  3. 可变长参数的使用规则

  3.1 在调用方法的时候,如果能够和固定参数的方法匹配,也能够与可变长参数的方法匹配,则选择固定参数的方法。看下面代码的输出:

package com;
// 这里使用了静态导入
import static java.lang.System.out;
public class VarArgsTest {
public void print(String... args) {
for (int i = 0; i < args.length; i++) {
out.println(args[i]);
}
}
public void print(String test) {
out.println("----------");
}
public static void main(String[] args) {
VarArgsTest test = new VarArgsTest();
test.print("hello");
test.print("hello", "alexia");
}
}