java中函数使用变长参数

来源:互联网 发布:印刷包装报价软件 编辑:程序博客网 时间:2024/05/16 04:15
java中函数使用变长参数
2010-01-01 21:09
当参数个数不确定时,开发者很想使用变长参数,让调用者以更灵活的方式调用。此种方法和方法重载有同样的效果,但是个人感觉比方法重载用着简洁。一直知道Java支持变长参数函数,然而项目中一直没有用到,前几天在项目中看到前辈大量使用变长参数,感觉有很好的效果。特别是API设计中能够解决很多不确定因素。下面是一个简单的变长参数示例
变长参数使用的形式是Type...argsName,即 类型+省略号+参数名
Java代码如下。
java code : 变长参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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]);
}
}
}
运行结果如下
1
2
3
4
5
6
7
8
9
10
Give no args
--------------------------
the args number is:2
args 0 is This is the first args
args 1 is This is the second args
--------------------------
the args number is:2
args 0 is This is the first args
args 1 is This is the second args
--------------------------


本文来自hi.baidu.com/yingnet,版权所有,转载请注明出处,谢谢合作

原创粉丝点击