Java变长参数

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

1、可变长参数方法的定义

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

print(String... args){

...

}

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

print(String... args){

for(String temp:args)

System.out.println(temp);

}

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

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

print("hello");

print("hello","lisi");

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

3、注意事项

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

package ch6;

import static java.lang.System.out;
public class VarArgsTest {

public static void main(String[] args) {
VarArgsTest test = new VarArgsTest();
test.print("hello");
test.print("hello","zhangsan");
}

public void print(String... args){
for(int i=0;i<args.length;i++){
out.println(args[i]);
}
}

public void print(String test){
out.println("----------");
}
}

3.2 如果要调用的方法可以和两个可变参数匹配,则出现错误,例如下面的代码:

package ch6;

import static java.lang.System.out;
public class VarArgsTest {

public static void main(String[] args) {
VarArgsTest test = new VarArgsTest();
test.print("hello");
test.print("hello","zhangsan");
}

public void print(String... args){
for(int i=0;i<args.length;i++){
out.println(args[i]);
}
}

public void print(String test,String...args ){
out.println("----------");
}
}

对于上面的代码,main方法中的两个调用都不能编译通过。

3.3 一个方法只能有一个可变长参数,并且这个可变长参数必须是该方法的最后一个参数

以下两种方法定义都是错误的。

public void test(String... strings,ArrayList list){

}

public void test(String... strings,ArrayList... list){

}

下面是一个有陷阱的例子(例子来源http://topic.csdn.net/u/20090515/23/54cca7cb-f9a**84f-9a25-1be1ab447ec8.html),请写出输出结果:

public class TestVarargs{
public static void m(String[] ss){
for(int i=0; i <ss.length; i++){
System.out.println(ss[i]);
}
}
public static void m1(String s, String... ss){
for(int i=0; i <ss.length; i++){
System.out.println(ss[i]);
}
}
public static void main(String[]args){
String[] ss = {"aaa", "bbb", "ccc"};
m(ss);
m1("");
m1("aaa");
m1("aaa", "bbb");
}
}

完毕!

李绪成 CSDN Blog:http://blog.csdn.net/javaeeteacher
CSDN学生大本营:http://student.csdn.net/space.php?uid=124362
如果喜欢我的文章,就加我为好友:http://student.csdn.net/invite.php?u=124362&c=7be8ba2b6f3b6cc5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值