Java Basics--Arrays

Table of contents

Declare and initialize an array:

Access and modify array elements:

Array length:

Iterate over the array:

Traversal of multidimensional arrays:

Common operations and methods for arrays:

Expand small knowledge:


Array is a data structure in Java used to store multiple elements of the same type. It provides a contiguous block of memory to store data, and can access and manipulate elements in the array through indexing.

Declare and initialize an array:

  • Array declaration: When declaring an array, you need to specify the data type and name of the array. For example, int[] myArray; declare an  myArray integer array named .
  • new Array initialization: Create an array object by using keywords  , and specify the length of the array or directly provide the initial value of the element to initialize the array.
    • Initialize the array by specifying the length: myArray = new int[5]; use  new the keyword to create an integer array containing 5 integer elements.
    • Directly provide the initial value of the element to initialize the array: int[] myArray = {1, 2, 3, 4, 5}; an integer array containing elements 1, 2, 3, 4 and 5 is defined and initialized.
int[] myArray;  // 声明一个整型数组变量
myArray = new int[5];  // 创建一个包含5个整数元素的数组

int[] myArray = {1, 2, 3, 4, 5};  // 声明并初始化一个整型数组

// 多维数组
int[][] myArray = new int[3][4];  // 声明一个3行4列的二维数组

Access and modify array elements:

  • The indexing of the array starts from 0, that is, the index of the first element is 0. To access and modify elements in an array, use square brackets  [] and provide the corresponding index.
    • Get the element value in the array: int value = myArray[0]; Get the element value with index 0 and assign it to the variable  value.
    • Modify the element value in the array: myArray[1] = 10; set the element value with index 1 to 10.
int value = myArray[0];  // 获取数组中索引为0的元素值

myArray[1] = 10;  // 修改数组中索引为1的元素值

Array length:

  • The length of the array can be obtained by using the length property of the array. For example, int length = myArray.length; gets the length of the array myArray and assigns it to the variable length.
int length = myArray.length;  // 获取数组的长度

Iterate over the array:

  • You can use looping constructs such as  for loops to iterate over the elements in an array and process them.
  • Use subscript to loop through: By controlling the range of the index, start from 0 to access the elements in the array one by one and perform operations.
for (int i = 0; i < myArray.length; i++) {
    System.out.println(myArray[i]);
}
  • Using for-each loop traversal: Using the for-each loop syntax can simplify the traversal operation of the array. It iterates through each element in the array in turn without explicitly using an index.
for (int num : myArray) {
    System.out.println(num);
}

Traversal of multidimensional arrays:

Multidimensional arrays are arrays of arrays. A nested loop structure can be used to iterate over the elements in a multidimensional array.

int[][] myArray = new int[3][4];  // 一个3行4列的二维数组

for (int i = 0; i < myArray.length; i++) {
    for (int j = 0; j < myArray[i].length; j++) {
        System.out.println(myArray[i][j]);
    }
}

Common operations and methods for arrays:

The java.util.Arrays class facilitates manipulation of arrays, and all methods provided by it are static.

The following is java.util.Arraysa brief introduction to the common methods provided by the class:

  1. fill method: fills the entire array with the specified value.
  2. sort method: sorts the array in ascending order.
  3. equals method: compares whether the element values ​​in two arrays are equal.
  4. binarySearch method: Use binary search method to find the specified element in the sorted array.

Note: When using an index to access and modify array elements, ensure that the index value is within the valid range of the array to avoid ArrayIndexOutOfBoundsExceptionexceptions.

import java.util.Arrays;

public class ArraysExample {
    public static void main(String[] args) {
        // 声明并初始化一个整型数组
        int[] array = {5, 2, 9, 1, 7};

        // 使用fill方法将整个数组填充为指定的值
        Arrays.fill(array, 0);
        System.out.println("使用fill方法后的数组: " + Arrays.toString(array));
        // 运行结果:使用fill方法后的数组: [0, 0, 0, 0, 0]

        // 使用sort方法对数组进行升序排序
        Arrays.sort(array);
        System.out.println("使用sort方法后的数组: " + Arrays.toString(array));
        // 运行结果:使用sort方法后的数组: [0, 0, 0, 0, 0]

        // 声明并初始化一个新的整型数组
        int[] newArray = {1, 2, 3, 4, 5};

        // 使用equals方法比较两个数组的元素值是否相等
        boolean isEqual = Arrays.equals(array, newArray);
        System.out.println("两个数组是否相等: " + isEqual);
        // 运行结果:两个数组是否相等: false

        // 使用binarySearch方法在已排序的数组中查找指定元素
        int index = Arrays.binarySearch(newArray, 4);
        System.out.println("查找元素的索引位置: " + index);
        // 运行结果:查找元素的索引位置: 3
    }
}

Expand small knowledge:

ArrayIndexOutOfBoundsException 是 Java 中的一个运行时异常,它表示数组访问超出了有效索引范围。这通常发生在以下情况下:

  1. Index less than zero: Attempt to use a negative number as the index of an array element.
    int[] myArray = {1, 2, 3};
    int value = myArray[-1];  // 导致 ArrayIndexOutOfBoundsException 异常
    
  2. Index greater than or equal to array length: An attempt was made to access or modify an index position that does not exist in the array.
    int[] myArray = {1, 2, 3};
    int value = myArray[3];  // 导致 ArrayIndexOutOfBoundsException 异常
    
  3. An index on one of the dimensions in a nested array (multidimensional array) is out of range.
    int[][] myArray = new int[3][4];  // 3行4列的二维数组
    int value = myArray[3][0];  // 导致 ArrayIndexOutOfBoundsException 异常
    

To avoid ArrayIndexOutOfBoundsExceptionexceptions, it is necessary to ensure that the index values ​​used are within the legal range when accessing and modifying array elements:

  • Arrays are indexed in the range of integers from 0 to length minus one (length - 1).
  • The index ranges for each dimension of a multidimensional array are also the same.

When writing code, you need to carefully check the use of array indexes to ensure that they are within the legal range, and you can use methods such as conditional judgment, loops, and boundary checks to avoid exceptions ArrayIndexOutOfBoundsException.

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/132257525