可变参数
是一种语法特性,它允许方法参数的个数不固定。在方法定义中,使用三个连续的点(…)来表示该参数可以接受多个值,这些值会被当作数组处理。例如:
public class Test10{
/**
需求:设计一个方法,传入n个int类型的值,返回最大值
*/
public static void main(String[] args){
int max = getMax(1,2,3,4,5,6,7);//将实参作为数组的元素传入
System.out.println(max);
}
//int... arr -- 可变参数,实际上就是数组
public static int getMax(int... arr){
if(arr.length == 0){//意味着实参没有传任何数据
return -1;
}
int max = arr[0];
for(int i = 1;i<arr.length;i++){
if(max < arr[i]){
max = arr[i];
}
}
return max;
}
//注意:可变参数后不能接其他参数
public static void method(int i,String... ss){
}
}