java方法中增加不固定参数

JDK1.5以上支持

一、定义方法

有时方法的参数个数不固定,可以使用...来省略个数,使用时直接遍历即可,例如下面的方法
public class hi {
public void print(String ...args){
    String str="";
    for (String t : args) {  //对输入的不确定个数参数进行取值操作
        str += t+ " ";
    }
    System.out.println("args = [" + str + "]");
}
public static void main(String[] args){
    new hi().print("1","2","3");
}
}

二、调用方法

1、最简单的直接向上面使用方法一样,直接传递参数1、参数2、参数3
new hi().print("1","2","3”);
 
2、使用数组传递
new hi().print(new String[]{"1","2","3"});
原文地址:https://www.cnblogs.com/meitian/p/8480869.html