[Summary] Declaration and initialization of one-dimensional arrays and two-dimensional arrays

[Summary] Declaration and initialization of one-dimensional arrays and two-dimensional arrays

1. Declaration and initialization of a one-dimensional array:
 1.1 Static initialization: the initialization of the array and the assignment of the array elements are carried out at the same time
 1.2 Dynamic initialization: the initialization of the array and the assignment of the array elements are carried out separately.
 
          Once the array is initialized, its length is determined .

Sample code:

int num;//声明
num = 10;//初始化
int id = 1001;//声明 +初始化
		
int[] ids;//声明
//1.1静态初始化:数组的初始化和数组元素的赋值操作同时进行
ids = new int[]{
    
    1001,1002,1003,1004};
//1.2动态初始化:数组的初始化和数组元素的赋值操作分开进行
String[] names = new String[5];

//如下也是正确的写法:
int[] arr4 = {
    
    1,2,3,4,5};//类型推断

Wrong way of writing:

int[] arry1 = new int[];
int[5] arry2 = new int[5];
int[] arry3 = new int[3]{
    
    1,2,3};

2. Declaration and initialization of two-dimensional arrays:
 2.1 Static initialization: the initialization of the array and the assignment of array elements are carried out at the same time. 2.
 2 Dynamic initialization: the initialization of the array and the assignment of array elements are carried out separately for
the understanding of the two-dimensional array , We can regard it as a one-dimensional array array1 as an element of another one-dimensional array array2. In fact, judging from the underlying operating mechanism of the array, there is no multidimensional array.

Sample code:

//1.二维数组的声明和初始化
int[] arr = new int[]{
    
    1,2,3};//一维数组
//静态初始化
int[][] arr1 = new int[][]{
    
    {
    
    1,2,3},{
    
    4,5},{
    
    6,7,8}};
//动态初始化1
String[][] arr2 = new String[3][2];
//动态初始化2
String[][] arr3 = new String[3][];

//如下也是正确的写法:
int[] arr4[] = new int[][]{
    
    {
    
    1,2,3},{
    
    4,5,9,10},{
    
    6,7,8}};
int[] arr5[] = {
    
    {
    
    1,2,3},{
    
    4,5},{
    
    6,7,8}};

Wrong way of writing:

int[][] arr4 = new int[4][3]{
    
    {
    
    1,2,3},{
    
    4,5},{
    
    6,7,8}};
String[][] arr5 = new String[][2];
String[4][3] arr2 = new String[][];

Guess you like

Origin blog.csdn.net/qq_45555403/article/details/114264459