码迷,mamicode.com
首页 > 编程语言 > 详细

java语言中的varargs

时间:2017-09-11 18:24:12      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:是什么   ...   传递   var   []   运行   转化   int   rar   

java语言中的varargs允许调用者传递数量不定的参数,并传入的数量不定的实参转化为数组形式的形参。

那么不传递任何参数,或者传入null时,形参的值是什么呢?下面是测试代码和运行结果:

 1     private void test1(int... args) {
 2         if (args != null) {
 3             System.out.println("[test1] args.length = " + args.length);
 4         } else {
 5             System.out.println("[test1] args is null");
 6         }
 7     }
 8 
 9     private void test2(String... args) {
10         if (args != null) {
11             System.out.println("[test2] args.length = " + args.length);
12         } else {
13             System.out.println("[test2] args is null");
14         }
15     }
16 
17     public void static main(String[] args) {
18         test1();
19         test1(null);
20         test1(1);
21         test1(1,2);
22 
23         test2();
24         test2(null);
25         test2("1");
26         test2("a", "b");
27     }

[test1] args.length = 0
[test1] args is null
[test1] args.length = 1
[test1] args.length = 2
[test2] args.length = 0
[test2] args is null
[test2] args.length = 1
[test2] args.length = 2

结论:

  1. 如果不传参数,那么形参的值是长度为0的数组。
  2. 如果传入null,那么形参的值是null,但是编译时会有警告提示。

 

java语言中的varargs

标签:是什么   ...   传递   var   []   运行   转化   int   rar   

原文地址:http://www.cnblogs.com/mopno1/p/7505666.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!