zoukankan      html  css  js  c++  java
  • java中重载变长参数方法

    一、测试代码

    package com.demo;
    public class Interview {
        public static void test(int i){
            System.out.println("call the test(int i)");
        }
        public static void test(int... ary){
            System.out.println("call the test(int... ary)");
            System.out.println(ary.length);
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            test();
            test(1,2,3);
            test(10);
            test(new int[]{1});
        }
    }

    二、输出结果

    call the test(int... ary)
    0
    call the test(int... ary)
    3
    call the test(int i)
    call the test(int... ary)
    1

    三、浅析

    1、可变参数的实际上调用过程实际上是将参数组织成一个数组,然后再出入该数组作为形参调用方法。

    例如test(1,2,3)的执行过程为:

           0: iconst_3
           1: newarray       int
           3: dup
           4: iconst_0
           5: iconst_1
           6: iastore
           7: dup
           8: iconst_1
           9: iconst_2
          10: iastore
          11: dup
          12: iconst_2
          13: iconst_3
          14: iastore
          15: invokestatic  #41                 // Method test:([I)V

    从newarray指令可以看出就是组织成数组的过程。
    2、test(int i)方法被重载了一个可变长度参数test(int... ary)

    那么

            test();//相当于执行test(new int[0])
            test(1,2,3);////相当于执行test(new int[]{1,2,3})

    3、test(10)调用了第一个方法,说明在同时定义了test(int i)和test(int... ary)的情况下,如果只传入一个参数:test(10),则test(int i)会被调用。

    那么在传入一个参数的情况下,如何调用test(int... ary)呢?可以通过test(new int[]{1});的方式来调用。

    四、数组形参和可变长度的形参的区别与联系

    区别:

    1、出现的位置不同:数组形式的形参可以出现形参的任意位置,但是可变长度的形参只能出现在形参列表的最后。

    2、数量不同:数组形式的形参可以有任意多个,但是可变长度的形参最多只能有一个。

    联系:

    变长度的形参本质上就是一个数组形参,因此调用一个可变长度形参的方法是,既可以传入多个参数,又可以直接传入数组参数。

    转载请注明来源:http://www.cnblogs.com/qcblog/p/7668080.html

  • 相关阅读:
    C++:delete和delete[]释放内存的区别
    C++:四种必须使用初始化列表情况
    C++:获取数组长度
    C++:构造函数默认的参数声明
    java 的开源wiki维基系统
    openfire 最大连接数调优
    即时通讯服务器的对比
    分分钟带你玩转 Web Services
    让git忽略ignore所有文件,只对某些文件进行版本控制
    miracast 协议wifi display
  • 原文地址:https://www.cnblogs.com/qcblog/p/7668080.html
Copyright © 2011-2022 走看看