数组三种初始化
-
静态初始化
int[] arrayInt = {1, 2, 3}; Schema[] schemas = {new Schema(), new Schema(), new Schema()};
-
动态初始化
int[] arrayInt = new int[3]; arrayInt[0] = 1; arrayInt[1] = 2; arrayInt[2] = 3;
-
默认初始化,数组是引用类型,其元素相当于类的实例变量,因此数组一经分配空间,其中的每个元素也被按照实例变量同样的方式被隐式初始化
-
程序案例:
public static void main(String[] args) { System.out.println("=====静态初始化====="); // 静态初始化 int[] arrayInt1 = {1, 2, 3}; System.out.println(arrayInt1[0]); System.out.println(arrayInt1[1]); System.out.println(arrayInt1[2]); System.out.println("=====动态初始化====="); // 动态初始化 int[] arrayInt2 = new int[5]; arrayInt2[0] = 1; arrayInt2[1] = 2; arrayInt2[2] = 3; System.out.println(arrayInt2[0]); System.out.println(arrayInt2[1]); System.out.println(arrayInt2[2]); System.out.println("=====默认初始化====="); // 定义了数组空间,但未对索引为3和4进行赋值,所以初始化整型的值为0,这就是默认初始化,整型默认值是0,字符串则是空 System.out.println(arrayInt2[3]); System.out.println(arrayInt2[4]); String[] arrayStr = new String[3]; arrayStr[0] = "This is A"; arrayStr[1] = "This is B"; System.out.println(arrayStr[0]); System.out.println(arrayStr[1]); System.out.println(arrayStr[2]); } // -------------------------------------- // 控制栏输出打印: /** =====静态初始化===== 1 2 3 =====动态初始化===== 1 2 3 =====默认初始化===== 0 0 This is A This is B null */