java中什么是不定长参数?

内容摘要
java中的不定长参数不定长度参数,就是没有规定长度的参数。不定长参数方法的语法如下:返回值 方法名(参数类型...参数名称)在参数列表中使用“...”形式定义不定长参数,其实这
文章正文

java中的不定长参数

不定长度参数,就是没有规定长度的参数。

不定长参数方法的语法如下:

1
返回值 方法名(参数类型...参数名称)

在参数列表中使用“...”形式定义不定长参数,其实这个不定长参数就是一个数组,编译器会将(int...a)这种形式看作是(int[] a)的形式。

示例:编写一个不定长参数方法。

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
/**
 * 定义不定长参数方法
 *
 * @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));
    }
}

运行结果:

1.jpg

代码注释
[!--zhushi--]

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!