可变参数的方法:
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()));
}
}