关闭

Java中可变长参数的使用及注意事项

发表于:2013-7-25 10:01

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Alexia    来源:51Testing软件测试网采编

  在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");
}
}

41/41234>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号