关于可变参数的补充说明

可变参数也可以是字符串,比如这样:

 1 package com.hw.ArrayListDemo0131;
 2 public class ChangeableMethod {
 3     public static void main(String[] args) {
 4         add("hello");
 5         System.out.println();
 6         add("hello","world");
 7     }
 8     public static void add(String... args){
 9         for(String str : args)
10         {
11             System.out.print(str+" ");
12         }
13     }
14 }

此外,关于可变参数还有一些注意事项如下:

1.可变参数指的是个数可变。

2.在调用方法的时候,如果既能够和固定参数的方法匹配,也能够和可变参数的方法匹配,优先调用固定参数的方法。

啥意思?这里涉及到方法的重载,意思就是说,如果我定义两个方法add方法,其中一个设置成固定参数的,另一个就采取这种可变参数的,那么在主方法里我如果要调用这个方法的话,如果只传一个参数进去,那么系统优先调用那个固定参数的,举个例子:

 1 package com.hw.ArrayListDemo0131;
 2 public class ChangeableMethod {
 3     public static void main(String[] args) {
 4         add("hello");
 5         System.out.println();
 6         add("hello","world");
 7     }
 8     
 9     public static void add(String stri){
10         System.out.println("固定参数"+stri);
11     }
12     
13     public static void add(String... args){
14         for(String str : args)
15         {
16             System.out.print(str+" ");
17         }
18     }
19 }

 

 可以看到,主方法里调用第一个add方法,只有一个"hello",显然两个方法都可调用,但通过运行结果来看,调用的是固定参数的。第二个add方法显然不能匹配第一个,就只能匹配第二个了。


3.一个方法里面只能有一个可变参数,同时,可变参数必须放在所有参数之后!

示例如下:

 1 package com.hw.ArrayListDemo0131;
 2 public class ChangeableMethod {
 3     public static void main(String[] args) {
 4         add(2,"hello","world","hahaha");
 5     }
 6     
 7     public static void add(int a,String str,String... args){
 8         System.out.println(a+str);
 9         System.out.println();
10         for(String string : args)
11         {
12             System.out.print(string+" ");
13         }
14     }
15 }

 

 可以看到,前面的2和hello都有参数可以匹配,后面的world和hahaha就只能匹配可变参数了。另外,可变参数还可传递0个参数过去。

 

posted @ 2021-02-05 09:16  EvanTheBoy  阅读(73)  评论(0)    收藏  举报