【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~