Removing an element from an Array in Java

There are a few different ways you can remove an element from an array in Java. Here are a few options:

  1. Using the ArrayList class:
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<>();
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);

    // Removing the element at index 1
    numbers.remove(1);
  }
}
  1. Using the System.arraycopy() method:
public class Main {
  public static void main(String[] args) {
    int[] numbers = {1, 2, 3};

    // Removing the element at index 1
    int[] newNumbers = new int[numbers.length - 1];
    System.arraycopy(numbers, 0, newNumbers, 0, 1);
    System.arraycopy(numbers, 2, newNumbers, 1, numbers.length - 2);
  }
}
  1. Manually shifting the elements:
public class Main {
  public static void main(String[] args) {
    int[] numbers = {1, 2, 3};

    // Removing the element at index 1
    for (int i = 1; i < numbers.length - 1; i++) {
      numbers[i] = numbers[i + 1];
    }
  }
}

Keep in mind that these approaches have different performance characteristics, and you should choose the one that is most appropriate for your use case.