看到如上所示的参数,当时就懵了。。。
如果,您已经很熟悉这种参数表示形式的话,对您来说阅读这篇文章是在浪费生命。
在说本篇文章主题之前,先扯会淡,且看!
public class Ubuntu {
public static void main(String[] args) {
String str = "";
System.out.println("str.length(): " + str.length());
String[] strArrays = new String[]{""};
System.out.println("strArrays.length(): " + strArrays.length);
System.out.println("strArrays[0].length(): " + strArrays[0].length());
}
}
这里主要想说明两个问题:
1. 判断字符串 String 的长度可以使用方法 length(), 判断字符串数组 String[] 的长度可以使用属性 length
2. ""对于字符串来说长度为0,但是对于数组来说表示字符数组中有一个长度为0的元素。
主角开始上场,实例代码如下:
public static void getInfo(String... str) { //可变参数
int len = str.length;
if(len <= 0) {
System.out.println("params's len is ZERO!");
}
for(int i=0; i<len; i++) {
System.out.println("str = " + str[i]);
}
}
由上面,可以看出
String... str 表示字符串数组,而不是字符串。因为调用 str.length 而不是调用 str.length()。
测试代码,如下:
public class Ubuntu {
public static void main(String[] args) {
getInfo("mark");
getInfo(new String[] {"simon", "amy", "jack", "mark"});
getInfo();
getInfo("");
}
}
显示结果:
str = mark
str = simon
str = amy
str = jack
params's len is ZERO!
str =
其中,params's len is ZERO!是 getInfo()的结果。str = 是getInfo("")的结果。
修改代码,如下:
public static void getInfo(String... str) { //可变参数
if(str == null) {
System.out.println("params is NULL!");
} else {
int len = str.length;
if(len <= 0) {
System.out.println("params's len is ZERO!");
}
for(int i=0; i<len; i++) {
System.out.println("str = " + str[i]);
}
}
}
public static void main(String[] args) {
getInfo(null);
}
结果:
params is NULL!
那么,是否支持基本数据类型呢?看下面代码,你就会明白啦???!!!
public static void getAge(int... num) {
if (num == null) {
System.out.println("params is NULL!");
} else {
int len = num.length;
if (len <= 0) {
System.out.println("params's len is ZERO!");
}
for (int i = 0; i < len; i++) {
System.out.println("num = " + num[i]);
}
}
}
public static void main(String[] args) {
getAge(1);
getAge(2, 3);
getAge();
getAge(null);
}
显示结果:num = 1
num = 2
num = 3
params's len is ZERO!
params is NULL!
ok,现在应该明白 Parameter... parameter 形式参数的含义了吧,就是用来表示可变数组,数组的类型不仅可以是引用类型还是基本数据类型。