A brief description of Java irregular arrays

The following code statically initializes an irregular array.

int intArray[][] = {
   
   {1,2}, {11}, {21,22,23}, {31,32,33}};

Irregular array

 It is troublesome to initialize irregular arrays dynamically. You cannot use the new int[4][3] statement. Instead, initialize the high-dimensional arrays first, and then initialize the low-dimensional arrays one by one. code show as below:

int intArray[][] = new int[4][]; //先初始化高维数组为4
// 逐一初始化低维数组
intArray[0] = new int[2];
intArray[1] = new int[1];
intArray[2] = new int[3];
intArray[3] = new int[3];

Irregular array access

class test09 
{
	public static void main(String[] args) 
	{
		int intArray[][] = new int[4][];   //初始化高维数组为4
		//逐一初始化低维数组
		intArray[0] = new int[2];
		intArray[1] = new int[1];
		intArray[2] = new int[3];
		intArray[3] = new int[3];
		//for 循环遍历
		for(int i = 0; i < intArray.length; i++){
			for(int j = 0; j < intArray[i].length; j++){
				intArray[i][j] = i + j;
			}
		}
		//for-each循环遍历
		for(int[] row : intArray){
			for(int val : row){
				System.out.print(val + "\t");
			}
			System.out.println();
		}
	}
}

 

Guess you like

Origin blog.csdn.net/qq_43629083/article/details/108628829
Recommended