当参数个数不确定时,开发者很想使用变长参数,让调用者以更灵活的方式调用。此种方法和方法重载有同样的效果,但是个人感觉比方法重载用着简洁。一直知道Java支持变长参数函数,然而项目中一直没有用到,前几天在项目中看到前辈大量使用变长参数,感觉有很好的效果。特别是API设计中能够解决很多不确定因素。下面是一个简单的变长参数示例
变长参数使用的形式是Type...argsName,即 类型+省略号+参数名
Java代码如下。
运行结果如下:
变长参数使用的形式是Type...argsName,即 类型+省略号+参数名
Java代码如下。
package varargsdemo;/** * * @author hitdong * @version 1.0 * @since 2010.1.1 */
public class Main { /** * @param args the command line arguments */
public static void main(String[] args) { /* * 不传递参数 */
printArgs();
System.out.println("--------------------------");
String arg1="This is the first args";
String arg2="This is the second args"; /* * 并列地传给多个参数 */
printArgs(arg1,arg2);
System.out.println("--------------------------"); String[] argsArray = new String[]{
arg1, arg2}; /* * 以数组方式传递多个参数 */
printArgs(argsArray);
System.out.println("--------------------------"); } /* *些函数接受类型为String的个数可变的参数,形参varargs是个数组 */
public static void printArgs(String...varargs){
int argsLength = varargs.length;
if(argsLength == 0){
System.out.println("Give no args");
}else{
System.out.println("the args number is:"+varargs.length); }
for (int i = 0; i < argsLength; i++) {
System.out.println("args "+i+" is "+varargs[i]); } }}
运行结果如下:
Give no args--------------------------the args number is:2args 0 is This is the first argsargs 1 is This is the second args--------------------------the args number is:2args 0 is This is the first argsargs 1 is This is the second args--------------------------