Java 可变参数

可变参数的方法:


package com.daxin;

/**
 * 
 * @author daxin
 * 
 * @email leodaxin@163com
 * 
 * @date 2017年4月18日 下午6:47:47
 * 
 */
public class Main1 {

	static String[] argsStr;

	static Object[] argsObj;
	public static void main(String[] args) throws Exception {
		/**
		 * 警告
		 * Type null of the last argument to method StringMethod(String...)
		 * doesn't exactly match the vararg parameter type. Cast to String[] to
		 * confirm the non-varargs invocation, or pass individual arguments of
		 * type String for a varargs invocation.
		 */
		StringMethod(null);//空指针异常
		StringMethod();
		StringMethod("1");
		StringMethod("1", "2");

	}

	public static void StringMethod(String... strs) {
		argsStr = strs;
		for (int i = 0; i < strs.length; i++) {
			System.out.println(strs[i]);
		}

	}

}


Java可变参数方法的变参数定义:类型 ... 参数名


传入参数关系和方法内部组成的数组关系:

调用:调用变参参数方法,如果传递阐述为null的话,则意味着变参数组成的数组为null

例如:StringMethod(null);调用,如果在方法实现中使用了数组的话,会报空指针异常,同时传递null参数时候编译器也会警告!

StringMethod(); //传递一个大小为0的数组,所以对于变参方法不传递值也是可以的
StringMethod("1"); //传递大小为1的数组
StringMethod("1", "2");//传递大小为2的数组


关于参数传入的类型:


1:如果我们的可变参数方法为

	public static void printString(String... args) {

		if (args == null) {
			return;
		}

		for (int i = 0; i < args.length; i++) {
			System.out.print(args[i] + " ");
		}

	}

如果此方式调用:printString("1", "2", "3", 4); //编译器报错:The method printString(String...) in the type JavaChar is not applicable for the arguments (String, String, String, int)


2:如果我们的可变参数方法为

	public static void printObject(Object... args) {

		if (args == null) {
			return;
		}

		for (int i = 0; i < args.length; i++) {
			System.out.print(args[i] + " ");
		}

	}

这样的话,printObject("1", "2", "3", 4);就可以正确调用了。虽然int是基本类型,但是可以装箱转成Integer,此处可以打印其类型验证:

	public static void printObject(Object... args) {

		if (args == null) {
			return;
		}

		for (int i = 0; i < args.length; i++) {
			System.out.println(args[i] + " "+(args[i].getClass().getName()));
			
		}

	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

javartisan

对您有帮助,欢迎老板赐一杯奶茶

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值