Detailed explanation of Java array--basic knowledge and common operations


foreword

In order to consolidate the knowledge learned, the author tried to start publishing some blogs of learning notes for future review. Of course, it would be great if it could help some newcomers learn new technologies. The author is a piece of food. If there are any mistakes in the records in the article, readers and friends are welcome to criticize and correct.
(The reference source code of the blog can be found in the resources on my homepage. If you have any questions during the learning process, please feel free to ask me in the comment area)

1. First familiarity with arrays

An array is a data structure that can hold multiple data elements of the same type . It is a commonly used data type in Java programming for storing and manipulating a set of data. An array provides a contiguous memory space to store multiple elements, and each element is accessed and manipulated through an index .

1. Definition of array

In Java, an array can be defined using the following syntax:

  dataType[] arrayName;

Among them, dataType represents the data type of elements in the array, and arrayName is the name of the array.

2. Characteristics of arrays

1. Arrays have the following characteristics:

  • The length of the array is fixed : once the array is created, its length is fixed and cannot be changed dynamically
  • .Store the same type of data : the elements in the array must be the same type of data
  • Continuous memory space : elements in the array are stored contiguously in memory and can be quickly accessed through indexes

insert image description here

  • It is precisely because the addresses of the array in the memory space are continuous, so when we delete or add elements, it is inevitable to move the addresses of other elements . For example, delete the element whose subscript is 3, as shown in the figure:

insert image description here

  • Array elements cannot be deleted, only overwritten

3. Declare and initialize the array

1. Syntax for declaring an array

To declare an array, you can use the following statement:

  dataType[] arrayName;

Among them, dataType is the data type of the elements in the array, and arrayName is the name of the array.

2. Static initialization and dynamic initialization

Initialization can be performed while declaring the array. Array initialization can be divided into static initialization and dynamic initialization.

  • static initialization

Static initialization refers to assigning initial values ​​to array elements while declaring the array. Static initialization can be done using the following syntax:

  dataType[] arrayName = {
    
    element1, element2, ...};

Among them, dataType is the data type of the elements in the array, arrayName is the name of the array, element1, element2 , ... are the values ​​to be assigned to the array elements.

  • dynamic initialization

Dynamic initialization refers to allocating memory space for the array after declaring the array, and assigning initial values ​​to the array elements. Dynamic initialization can be done using the following syntax:

  dataType[] arrayName = new dataType[arrayLength];

Among them, dataType is the data type of the elements in the array, arrayName is the name of the array, and arrayLength is the length of the array, indicating the number of elements that can be stored.

4. Default initialization value

In Java, if no initial value is assigned to the elements in the array, the array will automatically be initialized by default, and different default values ​​will be used depending on the data type . The following are default initialization values ​​for some common data types:

  • An array of int type, the default element value is 0
  • Array of double type, the default element value is 0.0
  • An array of boolean type, the default element value is false
  • An array of char type, the default element value is the null character \u0000

2. Access and manipulate array elements

1. Array index and range

Each element in the array is accessed by a non-negative integer index. Indexes start at 0 and increase sequentially. For example, the first element has index 0, the second element has index 1, and so on. The length of the array is n, then the valid index range is 0 to n - 1 .

2. Access array elements by index

To access elements in an array, the following syntax can be used:

  arrayName[index]

where arrayName is the name of the array and index is the index of the element to be accessed. This syntax can be used to get the element value at the specified index position in the array.

3. Modify the value of an array element

After accessing an array element through an index, you can also perform an assignment operation on the element to modify the value of the element. Use the following syntax to modify the value of an array element:

  arrayName[index] = newValue;

where arrayName is the name of the array, index is the index of the element to be modified, and newValue is the new value to be assigned to the element.

3. The length and properties of the array

1. Calculate the length of the array

The length of the array can be obtained by using the length property. The length indicates the number of elements in the array, not the size of the memory space occupied by the array. To get the length of an array, the following syntax can be used:

  int length = arrayName.length;

Among them, arrayName is the name of the array, and length is a variable used to store the length of the array.

2. The length attribute of the array

The length of the array is specified when the array is created, once created, the length is fixed. Use the length attribute to get the length value of the array, which is often used to traverse the array or check whether the array is out of bounds.

3. Array out of bounds error

When accessing array elements, you need to ensure that the index used is within the valid range, otherwise an array out-of-bounds error will occur. If the index is less than 0 or greater than or equal to the length of the array, an array out of bounds error will result. When writing code, you should pay special attention to the range of array indices .

Fourth, the traversal of the array

Array traversal refers to accessing each element in the array in turn. Traversing an array can be achieved through a loop structure, the common ones are for loop and enhanced for loop .

1. for loop to iterate through the array

for (int i = 0; i < arrayName.length; i++) {
    
    
    // 访问数组元素:arrayName[i]
    // 执行其他操作
}

In the for loop, use a loop variable i as the index, and gradually increase from 0 until the length of the array minus 1 is reached. This method is suitable for situations where operations based on indexes are required.

2. Enhance the for loop to traverse the array

for (dataType element : arrayName) {
    
    
    // 访问数组元素:element
    // 执行其他操作
}

The enhanced for loop is a simplified way of iterating through an array introduced in Java 5. It can directly traverse each element in the array without using index variables. This method is suitable for situations where you only need to access array elements without indexing.

3. Iterating over multidimensional arrays

Multiple loops can be nested to traverse multidimensional arrays, and each layer of loops is responsible for traversing elements of one-dimensional arrays.

for (int i = 0; i < arrayName.length; i++) {
    
    
    for (int j = 0; j < arrayName[i].length; j++) {
    
    
        // 访问数组元素:arrayName[i][j]
        // 执行其他操作
    }
}

Through nested loops, the elements of each two-dimensional array can be traversed in turn.

Five, multidimensional array

A multidimensional array is an array that contains multiple one-dimensional arrays . For example, a two-dimensional array is a common multidimensional array that contains multiple one-dimensional arrays as its elements.

1. Definition and initialization of two-dimensional array

In Java, two-dimensional arrays can be defined using the following syntax:

  dataType[][] arrayName = new dataType[rowLength][columnLength];

Among them, dataType is the data type of elements in the two-dimensional array, arrayName is the name of the two-dimensional array, rowLength indicates the number of rows of the two-dimensional array, and columnLength indicates the number of columns of the two-dimensional array.

Two-dimensional arrays can be initialized in two ways, static initialization and dynamic initialization, similar to one-dimensional arrays.

2. Access and manipulate two-dimensional array elements

To access elements in a two-dimensional array, the following syntax can be used:

  arrayName[rowIndex][columnIndex]

Among them, arrayName is the name of the two-dimensional array, rowIndex is the index of the row where the element to be accessed is located, and columnIndex is the index of the column where the element to be accessed is located.

Two-dimensional arrays can be manipulated by modifying the values ​​of the two-dimensional array elements. Similar to one-dimensional arrays, use the following syntax to modify element values ​​of two-dimensional arrays:

  arrayName[rowIndex][columnIndex] = newValue;

6. Notes and extensions of arrays

1. Immutability of array length

Once the array is created, its length is fixed and cannot be changed dynamically. If you need to store more elements, consider using a dynamic array or collection class.

2. Copy and sort array

  • Arrays can be copied using the System.arraycopy() method or the Arrays.copyOf() method

Use the System.arraycopy() method:

int[] sourceArray = {
    
    1, 2, 3, 4, 5};
int[] targetArray = new int[sourceArray.length];

System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

Use the Arrays.copyOf() method:

int[] sourceArray = {
    
    1, 2, 3, 4, 5};
int[] targetArray = Arrays.copyOf(sourceArray, sourceArray.length);
  • Arrays can be sorted using the Arrays.sort() method
 // 使用 Arrays.sort() 方法对数组进行排序
 Arrays.sort(numbers);
}

3. Array search

The binary search method can be used to perform binary search operations on sorted arrays through the binarySearch method

import java.util.Arrays;

public class BinarySearchExample {
    
    
    public static void main(String[] args) {
    
    
        // 示例数组,必须为已排序的数组
        int[] array = {
    
    10, 20, 30, 40, 50, 60, 70};
        int key = 40;

        int index = Arrays.binarySearch(array, key);
}

4. Realization of dynamic array: ArrayList

In Java, in addition to using arrays, you can also use the ArrayList class to implement dynamic arrays. ArrayList can automatically adjust the length, and provides a wealth of methods to manipulate and manage elements. (For details, please go to the personal homepage to view the entry blog about ArrayList)

Summarize

Everyone is welcome to leave a message for exchange and criticism. If the article is helpful to you or you think the author's writing is not bad, you can click to follow, like, and bookmark to support.
(The reference source code of the blog can be found in the resources on my homepage. If you have any questions during the learning process, please feel free to ask me in the comment area)

Guess you like

Origin blog.csdn.net/HHX_01/article/details/132164541