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。

  • 相关阅读:
    win10应用 UWP 使用MD5算法
    win10应用 UWP 使用MD5算法
    用git上传代码到新浪云
    用git上传代码到新浪云
    redis三节点sentinel部署
    [HNOI/AHOI2018]转盘
    用git上传代码到新浪云
    Windows-universal-samples-master示例 XamlCommanding
    Windows-universal-samples-master示例 XamlCommanding
    Windows-universal-samples-master示例 XamlCommanding
  • 原文地址:https://www.cnblogs.com/joshua-aw/p/6031859.html
Copyright © 2011-2022 走看看