How To Remove An Element In An Array Java

4 min read

How to Remove an Element in an Array Java
Removing an element from a Java array is a common task that trips up many beginners because native arrays have a fixed length. Unlike collections such as ArrayList, you cannot simply call a remove() method and expect the array to shrink. Instead, you must create a new array (or shift elements within the existing one) that excludes the unwanted value. This guide walks through several reliable techniques, explains when each is appropriate, and highlights performance considerations so you can choose the best approach for your situation Small thing, real impact..


Understanding Java Arrays

Before diving into removal strategies, recall that a Java array is a contiguous block of memory with a predetermined size declared at creation:

int[] numbers = {10, 20, 30, 40, 50}; // length = 5, cannot change

Because the length is immutable, any “removal” operation must produce a new array (or logically ignore the element) whose length is one less than the original. The core idea is to copy all elements except the one you want to drop into a fresh array Most people skip this — try not to..


Approaches to Remove an Element

There are three primary ways to achieve removal:

  1. Manual copying with a loop or System.arraycopy – works directly on primitive or reference arrays.
  2. Using utility methods from java.util.Arrays – concise, readable, and leverages optimized native code.
  3. Converting to a mutable collection (ArrayList), removing the element, then converting back – handy when you already work with lists or need multiple modifications.

Each method has trade‑offs in terms of code clarity, performance, and flexibility.


1. Manual Copy Using a Loop

The most explicit way is to iterate over the source array, skip the unwanted index, and write each kept element into a new array.

public static int[] removeElementLoop(int[] src, int indexToRemove) {
    if (indexToRemove < 0 || indexToRemove >= src.length) {
        throw new IllegalArgumentException("Invalid index");
    }
    int[] result = new int[src.length - 1];
    int j = 0;
    for (int i = 0; i < src.length; i++) {
        if (i == indexToRemove) {
            continue; // skip the element to remove
        }
        result[j++] = src[i];
    }
    return result;
}

Why use this?

  • Full control over the copying process (e.g., you can apply a filter while copying).
  • No external dependencies beyond core Java.
  • Works for both primitive and object arrays.

Performance note: The loop runs in O(n) time and touches each element once, which is optimal for a single removal.


2. Using System.arraycopy

When you know the index to remove, you can split the array into two parts—elements before the index and elements after it—and copy each segment with System.arraycopy, which is implemented in native code and often faster than a manual loop Simple, but easy to overlook. And it works..

public static int[] removeElementArrayCopy(int[] src, int index) {
    if (index < 0 || index >= src.length) {
        throw new IllegalArgumentException("Invalid index");
    }
    int[] result = new int[src.length - 1];
    // copy elements before the index
    System.arraycopy(src, 0, result, 0, index);
    // copy elements after the index
    System.arraycopy(src, index + 1, result, index, src.length - index - 1);
    return result;
}

Advantages:

  • Fewer lines of code; the intent is clear.
  • System.arraycopy can copy large blocks efficiently, making it suitable for big arrays.

When to prefer:

  • You already know the exact position of the element to drop.
  • You need maximum throughput for large data sets.

3. Using java.util.Arrays.copyOf and copyOfRange

The Arrays class offers helper methods that internally use System.arraycopy. You can combine copyOfRange to fetch the two slices and then concatenate them That alone is useful..

import java.util.Arrays;

public static int[] removeElementArrays(int[] src, int index) {
    if (index < 0 || index >= src.And arraycopy(right, 0, result, left. length);
    System.That's why length) {
        throw new IllegalArgumentException("Invalid index");
    }
    int[] left = Arrays. copyOfRange(src, index + 1, src.Still, copyOf(left, left. On the flip side, copyOfRange(src, 0, index);          // [0, index)
    int[] right = Arrays. length + right.So length); // (index, end]
    int[] result = Arrays. length, right.

**Why consider this?**  
- Readable if you already use `Arrays` for other operations (e.g., sorting, filling).  
- Leverages well‑tested library code.

---

### 4. Removing by Value (First Occurrence)

Sometimes you know the *value* you want to delete, not its index. You must first locate it, then apply one of the techniques above.

```java
public static int[] removeFirstOccurrence(int[] src, int value) {
    int index = -1;
    for (int i = 0; i < src.length; i++) {
        if (src[i] == value) {
            index = i;
            break;
        }
    }
    if (index == -1) {
        return src; // value not found – return original array
    }
    return removeElementArrayCopy(src, index);
}

Note: This returns a new array; the original remains unchanged Most people skip this — try not to..


5. In‑Place Shifting (Logical Removal)

If you cannot allocate a new array (e.g., in memory‑constrained environments), you can shift elements left over the unwanted slot and keep track of the new logical size But it adds up..

public static void removeInPlace(int[] arr, int index) {
    if (index < 0 || index >= arr.length) {
        throw new IllegalArgumentException("Invalid index");
    }
    for (int i = index; i < arr.length - 1; i++) {
        arr[i] = arr[i + 1];
    }
    arr[arr.length - 1] = 0; // optional: clear the duplicate tail
}

After calling this method, the array’s physical length stays the same, but you treat the last element as invalid. You must maintain a separate size variable or use a wrapper class to reflect the logical length.

Use case:

  • Working with APIs that expect a fixed‑size array but allow a “valid length” field (e.g., some native interfaces).

6. Using ArrayList for Flexibility

If you need to perform multiple removals or insertions, converting to an ArrayList simplifies the code:

import java.util.ArrayList;
import java.util.List;

public static int[] removeViaArrayList(int[] src, int value) {
Fresh Out

Recently Added

Others Liked

Picked Just for You

Thank you for reading about How To Remove An Element In An Array Java. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home