Detailed Java one-dimensional array and two-dimensional array (Java essential knowledge)

Array is the most common data structure, which is divided into first-level array, two-dimensional array and multi-dimensional array. It is a basic type data sequence or object sequence that encapsulates elements of the same data type with an identifier.

One-dimensional array

The data type of the array elements determines the data type of the array, which can be basic data types and other reference types. The symbol "[ ]" indicates that the variable is an array type variable. A single "[ ]" means a one-dimensional array.

Create a one-dimensional array

There are two ways to declare a one-dimensional array:

数组元素类型 数组名字[];
int a[];

数组元素类型[] 数组名字;
int[] b;

After declaring the array, you cannot access any of its elements, because declaring the array only gives the name of the array and the data type of the elements, and does not allocate memory space.

When declaring an array, you can allocate memory space for the array. This is to allocate the declaration and memory together for execution.

数组元素类型  数组名 = new 数组元素类型[数组元素的个数];
int month[] = new int[12];

Assign a value to a one-dimensional array

Arrays can be initialized the same as basic data types, that is, initial values ​​are assigned. The initialization of arrays can initialize each element in the array separately.

The initialization of the array has the following three forms:

int a[] = {
    
    1,2,3};          // 第一种方式
int[] b = new int[]{
    
    4,5,6}; // 第二种方式
int c[] = new int[3];	    // 第三种方式
c[0] = 7;					// 第一个元素赋值
c[1] = 8;					// 第二个元素赋值
c[2] = 9;					// 第三个元素赋值

Get the length of the array

Sometimes the array allocates space and we don't specify that at this time, we can get the length through arr.lenth.

int a[] = {
    
    1,2,3};   
System.out.println(a.length);

Common mistakes

Two-dimensional array

Two-dimensional arrays are often used to represent two-dimensional tables. The first element represents the row where the element is located, and the second subscript represents the column where the element is located.

Create a two-dimensional array

There are two ways to declare a two-dimensional array:

数组元素类型 数组名字[][];
int tdarr1[][];

数组元素类型[ ][ ] 数组名字;
int[][] tdarr2;

Like a one-dimensional array, a two-dimensional array is not allocated memory space when it is declared. The new keyword must also be used to allocate memory before the elements can be accessed.

There are two ways to allocate memory:

int a[][];
a = new int[2][3];	// 直接分配行列

int b[][];
b = new int[2][];	// 先分配行,不分配列
b[0] = new int[2];	// 给第一行分配列
b[1] = new int[2];	// 给第二行分配列

Note: To create a two-dimensional array, you can only declare the length of the row, but not the length of the column. The length of the line must be declared! ! !

Assign a value to a two-dimensional array

int tdarr1[][] = {
    
    {
    
    1,3,5},{
    
    4,6,7}};  			// 第一种方式

int tdarr2[][] = new int[][] {
    
    {
    
    1,3,5},{
    
    4,6,7}}; // 第二种方式

int tdarr3[][] = new int[2][3];					// 第三种方式
tdarr3[0] = new int[] {
    
    1,2,3};					// 给第一行分配一个一维数组
tdarr3[1][0] = 63;								// 给第二行第一列赋值为63
tdarr3[1][0] = 10;								// 给第二行第一列赋值为10
tdarr3[1][0] = 7;								// 给第二行第一列赋值为7

As can be seen from this example, each element of a two-dimensional array is also an array, so the first method of direct assignment, there are braces inside the braces, because each element is a one-dimensional array; the second method uses new The method is similar to a one-dimensional array. The third type is quite special. After the memory space is allocated, there are two assignment methods, either directly assigning a one-dimensional array to a row, or assigning a value to each element of a row separately.

Use scenarios of two-dimensional arrays

public static void main(String[] args) {
    
    
	char arr[][] = new char[4][];							// 创建二维数组,数组长度(行)为4
	arr[0] = new char[] {
    
     '春', '眠', '不', '觉', '晓' };	// 为每一行赋值
	arr[1] = new char[] {
    
     '处', '处', '闻', '啼', '鸟' };
	arr[2] = new char[] {
    
     '夜', '来', '风', '雨', '声' };
	arr[3] = new char[] {
    
     '花', '落', '知', '多', '少' };
	System.out.println("---横版---");
	for (int i = 0; i < 4; i++) {
    
    							// 循环4行
		for (int j = 0; j < 5; j++) {
    
    						// 循环5列
			System.out.print(arr[i][j]);					// 输出数组中的元素
		}
		if (i % 2 == 0) {
    
    
			System.out.print(",");							// 如果是1,3句输出逗号
		} else {
    
    		
			System.out.print("。");							// 如果是2,4句输出句号
		}
		// i行结束则换行(注意在哪个循环内执行)
		System.out.println();
	}
	System.out.println();
	System.out.println("---竖版---");
	for (int j = 0; j < 5; j++) {
    
    							// 列变行
		for (int i = 3; i >= 0; i--) {
    
    						// 行变列,反序输出			
			System.out.print(arr[i][j]);					// 输出数组中的元素
		}
		System.out.println();								// 换行
	}
	// 第5行单独输出标点符号
	System.out.println("。,。,");							// 输出最后的标点
}

running result:

Multidimensional Arrays

Those with higher dimensions than one-dimensional arrays are called multi-dimensional arrays. In theory, two-dimensional arrays also belong to multi-dimensional arrays. Java also supports three-dimensional arrays, four-dimensional arrays and other multi-dimensional arrays. The method of creating other multi-dimensional arrays is similar to that of two-dimensional arrays.

int a1[][][] = new int[3][4][5];				// 创建三维数组
char b1[][][][] = new char[6][7][8][9];			// 创建四维数组

Irregular array

Irregular arrays are supported in java. For example, in a two-dimensional array, the number of elements in different rows can be different:

int a[][] = new int[3][];		// 创建二维数组,指定行数,不指定列数
a[0] = new int[5];				// 第一行分配5个元素
a[1] = new int[3];				// 第二行分配3个元素
a[2] = new int[4];				// 第三行分配4个元素

Code example for outputting all elements in an irregular two-dimensional array:

public static void main(String[] args) {
    
    
	int a[][] = new int[3][];				// 创建二维数组,指定行数,不指定列数
	a[0] = new int[] {
    
    52,64,85,12,3,64};	// 第一行分配6个元素
	a[1] = new int[] {
    
    41,99,2};				// 第二行分配3个元素
	a[2] = new int[] {
    
    285,61,278,2};		// 第三行分配4个元素
	for (int i = 0; i < a.length; i++) {
    
    
		System.out.print("a[" + i +"]中有" + a[i].length + "个元素,分别是:");
		for (int tmp : a[i]) {
    
    				//foreach循环输出元素
			System.out.print(tmp + " ");
		}
		System.out.println();
	}
}

Output result:

Basic operation of array

Traversing a one-dimensional array is very simple and easy to understand. Traversing a two-dimensional array requires a double-layer for loop. The length of the array can be obtained through the length property of the array.

Iterate over the array

Code example:

public static void main(String[] args) {
    
    
	int b[][] = new int[][] {
    
    {
    
    1},{
    
    2,3},{
    
    4,5,6}}; // 定义二维数组
	for (int i = 0; i < b.length; i++) {
    
    
		for (int j = 0; j < b[i].length; j++) {
    
    
			System.out.print(b[i][j]);
		}
		System.out.println();
	}
}

Output result:

This grammar needs to be mastered: if there is a two-dimensional array a[][], a.length returns the number of rows in the array, and a[0].length returns the number of columns in the first row. In the same way, a[n] returns the number of columns in the n+1th row. Since the two-dimensional array may be an irregular array, it is better to use the length property to control the number of loops when traversing the two-dimensional array.

Fill and batch replace array elements

After the definition of the elements in the array is completed, the static method fill() of the Arrays class can be used to allocate the elements in the array, which has the effect of filling and replacement. The fill() method can assign the specified int value to the int type Each element of the array.

The syntax is as follows:

Array.fill(int[] a , int value)

a: The array to be allocated
value: the value of all elements in the array is to be stored

Code example:

public static void main(String[] args) {
    
    
	int arr[] = new int[5];
	arr[0] = 9;
	Arrays.fill(arr, 8);
	for (int i = 0; i < arr.length; i++) {
    
    
		System.out.println("第" + i + "个元素是: " + arr[i]);
	}
}

Output result:

Difficulties

Why does the array index start from 0?

This is to inherit the tradition of assembly language, starting from 0, it is convenient for the computer to do binary operations and search.

The length of the multidimensional array

The length property can only indicate the length of a one-dimensional array. When a two-dimensional array is used, the two-dimensional array is actually converted into a "one-dimensional array [one-dimensional array]" form, that is, the elements of a one-dimensional array are still a one-dimensional array .

Guess you like

Origin blog.csdn.net/weixin_43888891/article/details/113101059