Array of Java learning

Concept of array

  • Array concept: an array is a container with a fixed length for storing data to ensure that the data types of multiple data are consistent.

The so-called array is a set of elements of the same data type arranged in a certain order, that is, a limited number of variables of the same type are named with a name to manage them uniformly, and then they are distinguished by number. This name is called array name, and the number is called subscript or index. The variables that make up an array are called elements of the array. The number of elements in an array is called the length of the array.

Array features:

1. Once the length of the array is determined, it cannot be modified

2. Creating an array opens up a whole contiguous space in memory.

3. It is fast to access elements because you can directly locate any element through [subscript].

Definition of array

Method 1: static initialization

  • Format:
data type[] Array name = {Element 1,Element 2,Element 3...};//It must be completed in one statement and cannot be written separately
  • give an example:

Defines an array container that stores 1, 2, 3, 4, 5 integers

int[] arr = {1,2,3,4,5};//correct

int[] arr;
arr = {1,2,3,4,5};//error

Mode 2: static initialization

  • Format:
data type[] Array name = new data type[]{Element 1,Element 2,Element 3...};
or
 data type[] Array name;
Array name = new data type[]{Element 1,Element 2,Element 3...};
  • give an example:

Defines an array container that stores 1, 2, 3, 4, 5 integers.

int[] arr = new int[]{1,2,3,4,5};//correct

int[] arr;
arr = new int[]{1,2,3,4,5};//correct

int[] arr = new int[5]{1,2,3,4,5};//Wrong. If there is a {} specified element list after it, you don't need to specify the length in [length].

Mode 3: dynamic initialization

  • Format:
 The data type of the elements stored in the array[] Array name = new The data type of the elements stored in the array[length];
 
  or

 The data type stored in the array[] Array name;
 Array name = new The data type stored in the array[length];
  • Detailed explanation of array definition format:
    • Data types of elements stored in the array: what data types can the created array container store.
    • The type of element can be any Java data type. For example: int, String, Student, etc
    • []: represents an array.
    • Array name: name a variable for the defined array, which meets the identifier specification. You can use the name to operate the array.
    • New: keyword, the keyword used to create the array. Because the array itself is a reference data type, create an array object with new.
    • [length]: the length of the array, indicating how many elements can be stored in the array container.
    • Note: the array has the fixed length feature. Once the length is specified, it cannot be changed.
      • The same as the water cup, I bought a 2-liter water cup with a total capacity of 2 liters, neither more nor less.
  • give an example:

Define an array container that can store 5 integers. The code is as follows:

int[] arr = new int[5];

int[] arr;
arr = new int[5];

Access to array elements

  • Index: each element stored in the array will automatically have a number, starting from 0. This automatic number is called the array index, which can access the elements in the array through the index of the array.
  • Index range: [0, length of array - 1]
  • Format:
Array name[Indexes]
  • Index access to elements in the array:
    • Array name [index] = numeric value, assigning values to the elements in the array
    • Variable = array name [index], get the elements in the array
public static void main(String[] args) {
    //Define and store an array of int types, and assign elements 1, 2, 3, 4, 5
    int[] arr = {1,2,3,4,5};
    //Assign a value of 6 to the 0 index element
    arr[0] = 6;
    //Gets the element on the index of array 0
    int i = arr[0];
    System.out.println(i);
    //Direct output array 0 index elements
    System.out.println(arr[0]);
}

Traversal of array

  • Array length attribute: each array has a length and is fixed. Java gives an attribute to the array to obtain the length of the array. The statement is: array name. Length. The execution result of attribute length is the length of the array and the result of type int. It can be inferred from the times that the maximum index value of the array is the array name. length-1.
  • Array traversal: it is to get each element in the array separately, which is traversal. Traversal is also the cornerstone of array operations.
public static void main(String[] args) {
  	int[] arr = new int[]{1,2,3,4,5};
  	//Print the properties of the array, and the output result is 5
  	System.out.println("Length of array:" + arr.length);
    
    //Traverses the elements in the output array
    System.out.println("The elements of the array are:");
    for(int i=0; i<arr.length; i++){
        System.out.println(arr[i]);
    }
}

Default values for array elements

When we create an array using dynamic initialization:

 The data type of the elements stored in the array[] Array name = new The data type of the elements stored in the array[length];

At this time, only the length of the array is determined, and the value of the array element is not determined. In this case, the element defaults.

The elements of the array have default values:

Array memory graph

Memory overview

Memory is one of the important components of computer. It is a bridge to communicate with CPU. Its function is to temporarily store the operation data in the CPU and the data exchanged with external memory such as hard disk. As long as the computer is running, the CPU will transfer the data to be calculated to the memory for operation. When the operation is completed, the CPU will transmit the results. The program we write is stored in the hard disk. The program in the hard disk will not run. It must be put into the memory to run. After running, the memory will be emptied.

In order to run programs, Java virtual machine must allocate and manage memory space.

Memory partition of Java virtual machine

In order to improve the operation efficiency, the space is divided into different regions, because each region has a specific data processing mode and memory management mode.

Area nameeffect
Program counterThe program counter is a register in the CPU, which contains the address of the next instruction to be executed by each thread
Native Method Stack When the local method of native is invoked in the program, the memory area during the execution of the local method
Method areaStore class information, constants, static variables, code compiled by the real-time compiler and other data that have been loaded by the virtual machine.
Heap memoryStorage objects (including array objects), created by new, are stored in heap memory.
VM Stack It is used to store the local variable table of each Java method being executed, etc. The local variable table stores various basic data types and object references of known length during compilation. After the method is executed, it is automatically released.

Storage of arrays in memory

1. An array memory graph

public static void main(String[] args) {
  	int[] arr = new int[3];
  	System.out.println(arr);//[I@5f150435
}

Thinking: why print arr[ I@5f150435 , is it the address of the array?

A: it is not the address of the array.

Q: doesn't it mean that the first address of an array object is stored in arr?

A: the first address of the array is stored in arr, but because the array is a reference data type, when printing arr, the toString() method of the ARR array object will be called automatically. By default, this method implements the hexadecimal value of the object type name @ the hashCode() value of the object.

Q: is the hashCode value of the object the memory address of the object?

A: not necessarily, because this is related to the specific implementation of JVM products of different brands. For example, Oracle's OpenJDK provides five implementations, one of which is to directly return the memory address of the object, but OpenJDK does not select this method by default.

2. Why does the array subscript start with 0

Because the first element is 0 units away from the first address of the array.

3. Two array memory graphs

public static void main(String[] args) {
    int[] arr = new int[3];
    int[] arr2 = new int[2];
    System.out.println(arr);
    System.out.println(arr2);
}

4. Two variables point to an array

public static void main(String[] args) {
    // Define an array to store 3 elements
    int[] arr = new int[3];
    //Array index assignment
    arr[0] = 5;
    arr[1] = 6;
    arr[2] = 7;
    //Output element values on 3 indexes
    System.out.println(arr[0]);
    System.out.println(arr[1]);
    System.out.println(arr[2]);
    //Define the array variable arr2 and assign the address of arr to arr2
    int[] arr2 = arr;
    arr2[1] = 9;
    System.out.println(arr[1]);
}

Common exceptions in array usage

Array out of bounds exception

Look at the code and see what happens when it runs.

public static void main(String[] args) {
    int[] arr = {1,2,3};
    System.out.println(arr[3]);
}

Create an array and assign 3 elements. The index of the array is 0, 1 and 2. There is no 3 index, so we can't access the index that doesn't exist in the array. After the program runs, the array out of bounds exception of ArrayIndexOutOfBoundsException will be thrown. In the development, the out of bounds exception of the array cannot occur. Once it occurs, we must modify the code we write.

Array null pointer exception

Look at the code and see what happens when it runs.

public static void main(String[] args) {
    int[] arr = {1,2,3};
    arr = null;
    System.out.println(arr[0]);
}

The line of code arr = null means that the variable arr will not save the memory address of the array, so it is not allowed to operate the array. Therefore, a null pointerexception null pointer exception will be thrown during operation. In the development, the out of bounds exception of the array cannot occur. Once it occurs, we must modify the code we write.

Performance of null pointer exception in memory graph

Observe the following code and what results will appear after running:

	public static void main(String[] args){
		//Declare an array of String [] type to store the names of three students
		String[] names = new String[3];
		int count = names[0].length();
		System.out.println("Number of words in the first student's name:" + count);
	}

At present, the default value in names[0] is null, and then it calls the method to find the length of the string, which will report a null pointer exception.

Common operations for arrays

Array find latest value

Idea:

(1) First assume that the first element is Max / min

(2) Then compare max/min with the following elements one by one

  • Implementation idea:
    • Define variables to hold the elements on the index of array 0
    • Traverse the array to get each element in the array
    • Compare the traversed element with the variable that holds the value on the index of array 0
    • If the value of the array element is greater than the value of the variable, the variable records the new value
    • After the array loop is traversed, the variable saves the maximum value in the array

Example code:

int[] arr = {4,5,6,1,9};
//Find maximum value
int max = arr[0];
for(int i=1; i<arr.length; i++){
    if(arr[i] > max){
        max = arr[i];
    }
}

Find the most value and its subscript in the array

Case 1: find the maximum value and its subscript for the first time

Idea:

(1) First assume that the first element is Max / min

(2) max/min variable is used to represent the maximum / minimum value, and max/min is used to compare with the following elements one by one

(3) Use the index time to record the maximum / minimum subscript of the current comparison

Example code:

int[] arr = {4,5,6,1,9};
//Find maximum value
int max = arr[0];
int index = 0;
for(int i=1; i<arr.length; i++){
    if(arr[i] > max){
        max = arr[i];
        index = i;
    }
}

or

Idea:

(1) First assume that the first element is Max / min

(2) Use maxIndex to record the maximum / minimum subscript of the current comparison, then arr[maxIndex] is the current maximum value

int[] arr = {4,5,6,1,9};
//Find maximum value
int maxIndex = 0;
for(int i=1; i<arr.length; i++){
    if(arr[i] > arr[maxIndex]){
        maxIndex = i;
    }
}
System.out.println("Maximum:" + arr[maxIndex]);

Case 2: find the subscript of the maximum value and all its maximum values (i.e. the possible maximum value is repeated)

Idea:

(1) Find the maximum value first

① Assume that the first element is the largest

② Compare max with the following elements one by one

(2) Traverse the array to see which elements are the same as the maximum value

Example code:

int[] arr = {4,5,6,1,9};
//Find maximum value
int max = arr[0];
for(int i=1; i<arr.length; i++){
    if(arr[i] > max){
        max = arr[i];
    }
}

//Traverse the array to see which elements are the same as the maximum value
for(int i=0; i<arr.length; i++){
    if(max == arr[i]){
        System.out.print(i+"\t");
    }
}

Array statistics: sum, mean, even number, etc

Idea: traverse the array, accumulate one by one, and judge each element

Example code:

int[] arr = {4,5,6,1,9};
//Sum and mean
int sum = 0;//Because 0 plus any number does not affect the result
for(int i=0; i<arr.length; i++){
    sum += arr[i];
}
double avg = (double)sum/arr.length;

Example code 2:

int[] arr = {4,5,6,1,9};

//Total product
long result = 1;//Because multiplying 1 by any number does not affect the result
for(int i=0; i<arr.length; i++){
    result *= arr[i];
}

Example code 3:

int[] arr = {4,5,6,1,9};
//Count even numbers
int even = 0;
for(int i=0; i<arr.length; i++){
    if(arr[i]%2==0){
        even++;
    }
}

copy

Application scenario:

1. Capacity expansion
2. Backup
3. Intercept
4. Reverse

Example code: expand the capacity and add a new location to store 10

int[] arr = {1,2,3,4,5,6,7,8,9};

//If you want to expand the arr array, add 1 position
//(1) First create a new array, its length = the length of the old array + 1
int[] newArr = new int[arr.length + 1];

//(2) Copy element
//Note: I < arr.length because bit arr is shorter than newArr, avoid subscript out of bounds
for(int i=0; i<arr.length; i++){
    newArr[i] = arr[i];
}

//(3) Add the new element to the end of newArr
newArr[newArr.length-1] = 10;

//(4) If you continue to use arr below, you can make arr point to the new array
arr = newArr;

//(4) Traversal display
for(int i=0; i<arr.length; i++){
    System.out.println(arr[i]);
}

Example code: Backup

int[] arr = {1,2,3,4,5,6,7,8,9};

//1. Create a new array with the same length as the original array
int[] newArr = new int[arr.length];

//2. Copy element
for(int i=0; i<arr.length; i++){
    newArr[i] = arr[i];
}

//3. Traversal display
for(int i=0; i<arr.length; i++){
    System.out.println(arr[i]);
}

Example code: intercept [start, end] range

int[] arr = {11,22,33,44,55,66,77,88,99};

int start = 2;
int end = 6;

//1. Create a new array. The length of the new array = end start;
int[] newArr = new int[end-start];

//2. Assignment element
for(int i=0; i<newArr.length; i++){
    newArr[i] = arr[start + i];
}

//3. Traversal display
for(int i=0; i<newArr.length; i++){
    System.out.println(newArr[i]);
}

reversal

There are two methods:

1. With a new array

2. Head and tail corresponding position exchange

Example code of the first method:

int[] arr = {1,2,3,4,5,6,7,8,9};

//(1) Create a new array first
int[] newArr = new int[arr.length];

//(2) Copy element
int len = arr.length;
for(int i=0; i<newArr.length; i++){
    newArr[i] = arr[len -1 - i];
}

//(3) Discard the old and let arr point to the new array
arr = newArr;//Here, the first address of the new array is assigned to arr

//(4) Traversal display
for(int i=0; i<arr.length; i++){
    System.out.println(arr[i]);
}

Example code of the second method:

**Implementation idea: * * elements in the symmetrical position of the array are exchanged.

int[] arr = {1,2,3,4,5,6,7,8,9};

//(1) Calculate the number of times to exchange: number = arr.length/2
//(2) Head tail symmetrical position exchange
for(int i=0; i<arr.length/2; i++){//The number of cycles is the number of exchanges
    int temp = arr[i];
    arr[i] = arr[arr.length-1-i];
	arr[arr.length-1-i] = temp;
}

//(3) Traversal display
for(int i=0; i<arr.length; i++){
    System.out.println(arr[i]);
}
  • To achieve inversion, you need to exchange the elements at the symmetrical position of the array
  • Define two variables to hold the minimum index and maximum index of the array
  • Element exchange position on two indexes
  • Minimum index + +, maximum index –
  • The minimum index exceeded the maximum index, and the array inversion operation ended

	public static void main(String[] args){
		int[] arr = {1,2,3,4,5,6,7,8,9};

		//Head and tail exchange
		for(int min=0,max=arr.length-1; min<max; min++,max--){
		    //Head and tail exchange
		    int temp = arr[min];
		    arr[min] = arr[max];
			arr[max] = temp;
		}

		//(3) Traversal display
		for(int i=0; i<arr.length; i++){
		    System.out.println(arr[i]);
		}
	}

Tags: Java

Posted on Fri, 26 Nov 2021 04:02:42 -0500 by NottaGuru