zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    poj1006 Biorhythms ——中国剩余定理入门题
    hoj12614 Dictionary ——拓扑排序找环&&比赛残留题
    2013年4月23日 雨
    zoj1586 QS Network ——最小生成树入门题_Prim算法
    hoj12616 Median Tree ——最小生成树入门题&&比赛残留题_Kruscal算法
    tset3
    testhtml
    Oracle SQLID 与 Hash_value 算法及转换
    Linux 脚本中生成日志 set x
    test wrod
  • 原文地址:https://www.cnblogs.com/joshua-aw/p/6031859.html
Copyright © 2011-2022 走看看