一、数组三种声明方式
正确声明方法:
//第一种 声明 开辟内存空间 不能通过=赋值
int[] arr1 = new int[5];
//第二种 声明并赋值
int[] arr2 = new int[]{1,3,5,4,2};
//第三种等同于第二种 声明并赋值
int[] arr3 = {1,3,5,4,2};
错误声明方法:
//第一种:已知道数组初始值,不需要设置数组长度,[]中不能带3
int[] a=new int[3]{3,5,7};
//第二种:数组在声明时就需要被创建
int[] a; 或者 int[] a = null;
//a={3,5,7};
//第三种 相当于int[] arr = new int[0]; 属于错误用法一种,虽然可以编译通过
int[] arr = new int[]{};
二、动态参数
public class FormulaImpl implements Formula {
public static void main(String[] args) {
FormulaImpl Formula = new FormulaImpl();
Formula.test(1,2,3,4,5);
Formula.test(1,2);
Formula.test(1,2,4,5);
}
private void test(int ...params){
String outPutStr = "执行了test方法,携带动态参数列表。参数分别是:";
System.out.println();
for(int p : params){
outPutStr += p + " ";
}
System.out.println(outPutStr);
}
}
private void test(int ...params) 和 private void test(int[] params)本质是一样的,不能构成重载方法,会导致编译报错
错误
动态参数列表和数组参数的优势在于,他可以传0个参数
不传参数对比
动态参数使用两个规定
1、方法的参数列表中最多只有一个不定长度的参数;
2、就是不定长度的数组的位置必须是最后一个参数,不然不能通过编译。
正确写法:
private void test(int test1,int ...params){
String outPutStr = "执行了test方法,携带动态参数列表。参数分别是:";
System.out.println();
for(int p : params){
outPutStr += p + " ";
}
System.out.println(outPutStr);
}