Definition and application of array

Keywords: Java Back-end

1. Basic usage of array

1.1 what is an array

1.2 creating arrays

1.3 use of arrays

2. Array as parameter of method

2.1 basic usage

2.2 understanding reference types

2.3 understanding

3. Array as the return value of the method

4. Two dimensional array

1. Basic usage of array

1.1 what is an array

If you need to represent two data, you can directly create two variables int a; int b;
If you need to represent five data, you can create five variables int a1,a2,a3,a4,a5;
However, if you need to represent 10000 data, you can't create 10000 variables. At this time, you need to use arrays to help us create them in batch

An array is a collection that stores a set of data of the same data type, or an array can help us "batch" create the same variables.

1.2 creating arrays

There are three ways to create arrays in Java:

//dynamic initialization
 data type[] Array name = new data type [] { Initialization data };
int[] arr = new int[]{1, 2, 3};
//initiate static
 data type[] Array name = { Initialization data };
int[] arr = {1,2,3};
//Or:
data type[] Array name = new data type[Array length];
int[] arr = new int[3];

1.3 use of arrays

Use. Length to determine the array length:

int[] arr = new int[]{1,2,3,4,5};
System.out.println(arr.length);
//result:
5

The results show that the length of arr array is 5.5

To access elements in an array:

int[] arr = new int[]{1,2,3,4,5};
System.out.println(arr[4]);
//result:
5

Note: in Java, the array subscript starts from 0 and the array length is length, that is, the range of accessing subscript [0,length-1]. When the accessed subscript exceeds this range, the subscript out of bounds exception will occur, such as:

int[] arr = new int[]{1,2,3,4,5};
System.out.println(arr[-1]);

result:

This result indicates that the - 1 subscript of the arr array is out of bounds.

Traversal of array:
The so-called "traversal" refers to accessing all elements in the array without repetition and leakage. It usually needs to be combined with circular statements

Use the for loop to traverse the array:

int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
	System.out.print(arr[i]+" ");
}
//result:
1 2 3 4 5 

Use the for each loop to traverse the array:

int[] arr = {1, 2, 3,4,5};
for (int x : arr) {
	System.out.print(x+" ");
}
//result:
1 2 3 4 5 

The for each loop is another way to use the for loop. It can more easily complete the traversal of the array and avoid the wrong writing of the loop conditions and update statements, but the for each loop cannot obtain the subscript of the array.

2. Array as parameter of method

2.1 basic usage

Transfer the array in the main method to the print method and output:

public static void main(String[] args) {
	int[] arr = {1, 2, 3, 4, 5};
	print(arr);
}
public static void print(int[] a) {
	for (int x : a) {
		System.out.print(x+" ");
	}
}
//result:
1 2 3 4 5

int[] a is the formal parameter of the function, and int[] arr is the argument of the function
If you need to get the array length, you can also use a.length

2.2 understanding reference types

We all know that when we assign an argument to a formal parameter and exchange the value of the formal parameter, the value of the argument will not change. For the array:

public static void main(String[] args) {
int[] arr = {1, 2, 3};
func(arr);
System.out.println("arr[0] = " + arr[0]);
}
public static void func(int[] a) {
a[0] = 10;
System.out.println("a[0] = " + a[0]);
}
// results of enforcement
a[0] = 10
arr[0] = 10

Obviously, when the array name is used as a parameter, the value of the formal parameter is changed, and the value of the actual parameter is also changed. At this time, the array name arr is a "reference". When passing parameters, the parameters are passed by reference

So how to understand? First, let's start with memory.

How to understand memory?
Memory can be intuitively understood as a dormitory building. There is a long corridor with many rooms on it. The size of each room is 1 Byte. There is a house number on each room, which is called the address.
What is a reference?
We mentioned that in the above example, the array name arr is a reference. When creating this reference, only a small variable is created on the stack, which stores an address of an array on the heap.

As shown in the figure, we define a reference type variable arr on the stack, which stores the address of an array on the heap, that is, it points to the array with address 0x999. In essence, the so-called "reference" only stores an address. Java sets the array as the reference type. In this way, the subsequent array parameter transfer is actually just to pass the address of the array into the function parameter. For example, in the above example, the address of the array pointed to by arr is passed to a, that is, both arr and a point to this array, When we modify the value of the array through a in the func method, the value of the array pointed to by arr in the main method will naturally change.

2.3 understanding

null represents an empty reference in Java, that is, an invalid reference.

int[] arr = null;
System.out.println(arr[0]);
// Compilation produces errors
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:6)

The function of NULL is similar to NULL (NULL pointer) in C language. They all represent an invalid memory location. Therefore, no read and write operations can be performed on this memory. Once you try to read and write, an error will occur.

3. Array as the return value of the method

: write a method to * 2 each element in the array:

class Test {
	public static void main(String[] args) {
		int[] arr = {1, 2, 3};
		int[] output = transform(arr);
		printArray(output);
	}
	public static void printArray(int[] arr) {
		for (int i = 0; i < arr.length; i++) {
		System.out.println(arr[i]);
	}
}
	public static int[] transform(int[] arr) {
		int[] ret = new int[arr.length];
		for (int i = 0; i < arr.length; i++) {
			ret[i] = arr[i] * 2;
		}
		return ret;
	}
}

When defining a method, the method type is int [], which returns an array.

4. Two dimensional array

Define a two-dimensional array (3 definition methods):

int[][] array1 = {{1,2,3},{4,5,6}};
int[][] array2 = new int[][] {{1,2,3},{4,5,6}};
int[][] array3 = new int[2][3];	

A two-dimensional array is composed of multiple one bit arrays. In Java, a one bit array is used to represent the number of rows of the array. Each row of the array stores the address of the row array, and each row uses an array to store all elements of the row, such as:

In the above two-dimensional array, the array has two rows and three columns. The array array is used to store the number of rows of the array, the 0 subscript is used to store the first address of the array in row 0, and the 1 subscript is used to store the first address of the array in row 1. Each row uses an array to store the elements of this row.

Print 2D array:
First:

int[][] array = {{1,2,3},{4,5,6}};
for(int i=0;i<array.length;i++)
{
	for(int j=0;j<array[i].length;j++)
	{
		System.out.print(array[i][j]+" ");
	}
	System.out.println();
}
//result:
1 2 3
4 5 6

Or replace the for loop with the for each loop:

int[][] array = {{1,2,3},{4,5,6}};
for(int ret[]:array){
	for(int X:ret){
		System.out.print(X+" ");
	}
	System.out.println();
}
//result:
1 2 3
4 5 6

Second printing:

int[][] array = {{1,2,3},{4,5,6}};
System.out.println(Arrays.deepToString(array));
//result:
[[1,2,3],[4,5,6]]

Define an irregular two-dimensional array
First:

int[][] array = new int[2][];
array[0] = new int[ ]{1,2};
array[1] = new int[]{4,5,6};
System.out.println(Arrays.deepToString(array));
//result:
[[1, 2], [4, 5, 6]]

Second:

int[][] array = {{1,2},{4,5,6}};
System.out.println(Arrays.deepToString(array));
//result:
[[1, 2], [4, 5, 6]]

The end

Posted by l!m!t on Wed, 27 Oct 2021 22:02:40 -0700