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。

  • 相关阅读:
    WPF 本地化语言设置
    WPF 调节树状图滚动条值
    WPF中ListBox的使用注意事项
    SQL 树状结构表中查出所所有父级/子级
    Vue创建
    wpf 控件注意事项
    链表习题(1)-设计一个递归算法,删除不带头结点的单链表L中所有值为x的结点
    排序-快速排序
    排序-堆排序
    图-图的遍历
  • 原文地址:https://www.cnblogs.com/joshua-aw/p/6031859.html
Copyright © 2011-2022 走看看