zoukankan      html  css  js  c++  java
  • 【java入门点滴】String... args VS String[] args

    动态参数 String... args,可以传递0~N个参数;

    数组参数 String[] args,需要实例化或者指定为null ;(方法内部需要对null进行判定)

    //利用动态参数进行参数传递
    public static void sayHello(String... args) { for (String s : args) { System.out.println("hi," + s); } }
    //利用数组进行参数传递
    public static void sayArrayHello(String[] args) { for (String s : args) { System.out.println("hi," + s); } }

    编译后的代码如下:

    public static void sayHello(String... args) {
            String[] arr$ = args;
            int len$ = args.length;
    
            for(int i$ = 0; i$ < len$; ++i$) {
                String s = arr$[i$];
                System.out.println(s);
            }
    
        }
    
     public static void sayArrayHello(String[] args) {
            String[] arr$ = args;
            int len$ = args.length;
    
            for(int i$ = 0; i$ < len$; ++i$) {
                String s = arr$[i$];
                System.out.println(s);
            }
    
        }

    个人认为两者此时,编译后的代码是相同的。

    那么,他们两个又有哪些区别呢?

    区别一、动态参数可以有任意多个,而且是可以作为缺省;而数组参数,需要实例化或者指定为null ;(方法内部需要对null进行判定);

        public static void sayHello(Boolean sayProfix, String... args) {
            for (String s : args) {
                System.out.println(sayProfix + s);
            }
        }
    
        public static void sayArrayHello(Boolean sayProfix, String[] args) {
            for (String s : args) {
                System.out.println(sayProfix + s);
            }
        }

    调用方:

            sayHello(true, "a", "b", "c", "d");
            sayHello(false);//依然可以正常执行
            System.out.println("end string... args");
    
            sayArrayHello(true, new String[]{"_a", "_b", "_c", "_d"});
            sayArrayHello(false, new String[]{});//必须声明一个数组
            System.out.println("enf of string[] args");

    其实,更多的还是在于调用方的区别。动态参数(String...) 类似于C#中的参数设置了默认值,在传递时,如果不传递,将默认使用指定的默认值;

    public static void Csharp(bool sayProfix,string content="",int flag=1 )
    {
       //todo   
    }

    that's all.

    点滴积累,每天进步一点点!O(∩_∩)O~
  • 相关阅读:
    大数据Hadoop第二周——配置新的节点DataNode及ip地址
    vue环境搭建详细步骤
    苹果电脑Mac系统如何下载安装谷歌Chrome浏览器
    点云的基本特征和描述
    ModuleNotFoundError: No module named 'rospkg'
    ROS的多传感器时间同步机制Time Synchronizer
    Spring Cloud 2020 版本重大变革,更好的命名方式!
    Spring MVC 接收请求参数所有方式总结!
    阿里为什么不用 Zookeeper 做服务发现?
    微服务之间最佳调用方式是什么?
  • 原文地址:https://www.cnblogs.com/hager/p/5390412.html
Copyright © 2011-2022 走看看