java中函数使用变长参数

系统 1431 0
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 ,版权所有,转载请注明出处,谢谢合作

java中函数使用变长参数


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论