variable parameter
-
Starting with JDK 1.5, Java supports passing variable parameters of the same type to a method.
-
In the method declaration, add an ellipsis (···) after the specified parameter type . –> test(int…i)
-
Only one variable parameter can be specified in a method, and it must be the last parameter of the method . Any ordinary parameters must be declared before it.
public static void main(String[] args) {
Demo04 demo04 =new Demo04();
demo04.test(2,3,4,0,90); //通过demo04来调用test
}
public void test(int...i){
System.out.println(i[0]);
System.out.println(i[1]);
System.out.println(i[2]);
System.out.println(i[3]);
System.out.println(i[4]);//最后输出竖着排列的 2,3,4,0,90
}
public static void main(String[] args) {
//调用可变参数的方法
printMax(38,40,2,403,39.3,39);
printMax(new double[]{
1,2,3});
/*最后输出结果是:
The max value is403.0
The max value is3.0
*/
}
public static void printMax(double... numbers){
if (numbers.length==0){
System.out.println("No argument passed");
return;
}
double result =numbers[0];
//排序
for (int i=1;i<numbers.length;i++){
if (numbers[i]>result){
result = numbers[i];
}
}
System.out.println("The max value is" +result);
}
}