How to remove a specific element from a Java array?

In Java, arrays are fixed-length data structures and cannot directly remove elements. However, you can achieve the effect of deleting a specific element by following these steps:

  1. Iterate through the array to find the index position of the element to be deleted.
  2. Create a new array with one less element than the original array.
  3. Copy all elements from the original array except for the ones to be deleted to a new array.
  4. Assign the new array to the original array.

Here is an example code showing how to remove a specified element.

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        int element = 3;

        // 找到要删除的元素的索引位置
        int index = -1;
        for (int i = 0; i < array.length; i++) {
            if (array[i] == element) {
                index = i;
                break;
            }
        }

        // 如果找到了要删除的元素,则进行删除操作
        if (index != -1) {
            // 创建一个新的数组
            int[] newArray = new int[array.length - 1];

            // 将原数组中除了要删除的元素之外的其他元素复制到新数组中
            for (int i = 0, j = 0; i < array.length; i++) {
                if (i != index) {
                    newArray[j++] = array[i];
                }
            }

            // 将新数组赋值给原数组
            array = newArray;
        }

        // 输出删除元素后的数组
        for (int i : array) {
            System.out.println(i);
        }
    }
}

In the example above, we will remove element 3 from the array and output the result after removing the element.

bannerAds