Java(JDK > 1.5) 支持传递同类型的可变参数给一个方法。一个方法中只能指定一个可变参数,它必须是方法的最后一个参数,在指定参数类型后加一个省略号(...) 。
方法的可变参数的声明如下所示:
typeName... parameterName
实例:
public class Test {
public static void main(String args[]) {
// 调用可变参数的方法
printMax("data", "number", "letter");
printMax(new String[]{"happy", "fun", "lucky", "happiness"});
}
public static void printMax( String... lookup) {
if (lookup.length == 0) {
System.out.println("No argument passed");
return;
}
String result = lookup[0];
for (int i = 1; i < lookup.length; i++){
if (lookup[i].length() > result.length()) {
result = lookup[i];
}
else if(lookup[i].length() == result.length()){
System.out.println(result + " and " + lookup[i] + " : Both strings are the same length");
}
}
System.out.println("The maximum field of \"lookup\" is : " + result);
}
}
结果展示:
number and letter : Both strings are the same length
The maximum field of "lookup" is : number
happy and lucky : Both strings are the same length
The maximum field of "lookup" is : happiness
来源:CSDN
作者:*MuYu*
链接:https://blog.csdn.net/qq_36535820/article/details/103968042