现在的位置: 首页 > 综合 > 正文

Java变长参数

2013年09月16日 ⁄ 综合 ⁄ 共 2006字 ⁄ 字号 评论关闭

在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

【上篇】
【下篇】

抱歉!评论已关闭.