Parameter... parameter

看到如上所示的参数,当时就懵了。。。

如果,您已经很熟悉这种参数表示形式的话,对您来说阅读这篇文章是在浪费生命。

在说本篇文章主题之前,先扯会淡,且看!

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 形式参数的含义了吧,就是用来表示可变数组,数组的类型不仅可以是引用类型还是基本数据类型。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值