java传参数时 类型后跟3个点“...”的意义

可变数组参数。用…的话,传参数时可传可不传,传的话,可以是一个个并列地传,也可以直接是一个数组。

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 public class StringDemo{  
public static void main(String[] args){
testPoints("I love my job.");//一个参数传入
testPoints("you","and","me");//3个String参数传入
testPoints(new String[]{"you","and","me"});//可以看到传入三个String参数和传入一个长度为3的数组结果一样,再看例子
System.out.println("---------------------------------------------------------");

testPoints(7);
testPoints(7,9,11);
testPoints(new Integer[]{7,9,11});
}

public static void testPoints(String... s){
if(s.length==0){
System.out.println("没有参数传入!");
}else if(s.length==1){
System.out.println("1个参数传入!");
}else{
System.out.println("the input string is-->");
for(int i=0;i<s.length;i++){
System.out.println("第"+(i+1)+"个参数是"+s[i]+";");
}
System.out.println();
}
}

public static void testPoints(Integer... itgr){
if(itgr.length==0){
System.out.println("没有Integer参数传入!");
}else if(itgr.length==1){
System.out.println("1个Integer参数传入!");
}else{
System.out.println("the input string is-->");
for(int i=0;i<itgr.length;i++){
System.out.println("第"+(i+1)+"个Integer参数是"+itgr[i]+";");
}
System.out.println();
}
}

}

================================
输出:
1个参数传入!
the input string is-->
1个参数是you;
2个参数是and;
3个参数是me;

the input string is-->
1个参数是you;
2个参数是and;
3个参数是me;

================================
1个Integer参数传入!
the input string is-->
1个Integer参数是7;
2个Integer参数是9;
3个Integer参数是11;

the input string is-->
1个Integer参数是7;
2个Integer参数是9;
3个Integer参数是11;