JDK5-可变参数
Posted Joshua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDK5-可变参数相关的知识,希望对你有一定的参考价值。
如:public void function(int arg, int... args)
注意:
可变参数必须出现在参数列表的最后,否则使用数组
可变参数隐式地创建一个数组
如下程序:
1 public class VarParameter { 2 3 public static void main(String[] args) { 4 // TODO Auto-generated method stub 5 printArr(1, 2, 3); 6 printArr(new Integer[] { 1, 2, 3 }); 7 printArr(new int[] { 1, 2, 3 }); 8 printArr("1", "2", "3"); 9 printArr(new String[] { "1", "2", "3" }); 10 printArr(new Object[] { new String[] { "1", "2", "3" } }); 11 printArr((Object) new String[] { "1", "2", "3" }); 12 } 13 14 private static void printArr(Object... args) { 15 System.out.println(args.length); 16 } 17 }
输出结果为:
3 3 1 3 3
1
1
分析:
1. 传递参数为1,2,3时,隐式地构造args = new Object[]{1, 2, 3};
2. 传递参数为new Integer[]{1,2,3}时,隐式地将Integer数组转变为Object数组
3. 传递参数为new int[]{1,2,3}时,将int[]转变为Object,因此Object数组的长度只有一(基本类型无法直接转变为Object)
4. 传递参数为"1","2","3"时,隐式地构造args = new Object[]{"1", "2", "3"};
5. 传递参数为new String[]{"1", "2", "3"}时,隐式地将String数组转变为Object数组
6. 传递参数为new Object[] {new String[]{"1", "2", "3"}}时,将String数组作为Object数组的一个元素进行传递
7. 传递参数为(Object)new String[]{"1", "2", "3"}时,强制地将String数组转变为Object类型(数组的Superclass为Object)
1 import java.util.Arrays; 2 import java.util.List; 3 4 public class VarParameter { 5 6 public static void main(String[] args) { 7 List list = Arrays.asList(new int[]{1,2,3}); 8 System.out.println(list.size()); 9 } 10 }
同样的道理,本程序的输出结果也为1。
以上是关于JDK5-可变参数的主要内容,如果未能解决你的问题,请参考以下文章