How to remove a specified element from a Java array?

You can remove a specific element from a Java array by using the following method:

  1. Create a new array and copy all elements from the original array except for the specified position to the new array. The System.arraycopy() method can be used to achieve this.

For example, let’s say we want to remove an element at the position index:

int[] originalArray = {1, 2, 3, 4, 5};
int[] newArray = new int[originalArray.length - 1];

System.arraycopy(originalArray, 0, newArray, 0, index);
System.arraycopy(originalArray, index + 1, newArray, index, originalArray.length - index - 1);

for (int num : newArray) {
    System.out.print(num + " ");
}

The output result is 1 2 4 5.

  1. Delete the element at a specific position using an ArrayList and then convert the ArrayList back into an array.
import java.util.ArrayList;

int[] originalArray = {1, 2, 3, 4, 5};
ArrayList<Integer> arrayList = new ArrayList<>();

for (int num : originalArray) {
    arrayList.add(num);
}

int index = 2; // 指定要删除的位置
arrayList.remove(index);

int[] newArray = new int[arrayList.size()];

for (int i = 0; i < arrayList.size(); i++) {
    newArray[i] = arrayList.get(i);
}

for (int num : newArray) {
    System.out.print(num + " ");
}

The output will be: 1 2 4 5

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds