java中不定长参数的实例用法
java中不定长参数的使用方法
不定长参数方法的语法如下:
返回值 方法名(参数类型...参数名称)
在参数列表中使用“...”形式定义不定长参数,其实这个不定长参数a就是一个数组,编译器会将(int...a)这种形式看作是(int[] a)的形式。
示例:编写一个不定长参数方法。
/**
 * 定义不定长参数方法
 * 
 * @author pan_junbiao
 *
 */
public class MyTest
{
  public static int add(int... a)
  {
    int s = 0;
    for (int i = 0; i < a.length; i++)
    {
      s += a[i];
    }
    return s;
  }
  public static void main(String[] args)
  {
    // 调用不定长参数方法
    System.out.println("调用不定长参数方法:" + add(1, 2, 3, 4, 5, 6, 7, 8, 9));
    System.out.println("调用不定长参数方法:" + add(1, 2));
  }
}
运行结果:
调用不定长参数方法:45
调用不定长参数方法:3
知识点扩展:
可变长参数的使用规则
在调用方法的时候,如果能够和固定参数的方法匹配,也能够与可变长参数的方法匹配,则选择固定参数的方法。看下面代码的输出:
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");
  }
}
以上就是本次介绍的全部相关知识点内容,如果大家有任何补充可以联系我们的小编。
 赞 (0)
                        
