How do you remove data from a Java array?

In Java, the length of an array is fixed and cannot be changed once it is defined. However, you can achieve the effect of deleting data by creating a new array and excluding the data you want to remove. The specific steps are as follows:

  1. Define a new array with a length one less than the original array. For example, if the original array has a length of n, the new array will have a length of n-1.
  2. Traverse the original array, exclude the data to be deleted, and copy the remaining elements to a new array.
  3. Lastly, assign the new array to the original array.

Here is an example code:

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int[] newArr = new int[arr.length - 1];
        int deleteIndex = 2; // 要删除的元素的索引

        for (int i = 0, j = 0; i < arr.length; i++) {
            if (i != deleteIndex) {
                newArr[j] = arr[i];
                j++;
            }
        }
        
        arr = newArr;
        
        // 打印删除后的数组
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

The output is: 1 2 4 5, which means the element at index 2 was deleted from the original array.

广告
Closing in 10 seconds
bannerAds