Removing an element from a Java array involves creating a new array, excluding the specified element, and shifting the remaining elements as arrays are of fixed size. Alternatively, you can use ArrayList
for easier element removal due to its dynamic nature.
Remove Element Using a New Array
This program creates a smaller array, excluding the specified element by shifting the remaining elements.
package com.javacodepoint.array;
public class RemoveElement {
public static void main(String[] args) {
int[] arr = { 10, 20, 30, 40, 50 };
int removeIndex = 2; // Index of the element to be removed
// Create a new array of size n-1
int[] newArr = new int[arr.length - 1];
// Copy elements to the new array, skipping the element to be removed
for (int i = 0, j = 0; i < arr.length; i++) {
if (i != removeIndex) {
newArr[j++] = arr[i];
}
}
// Print the new array
System.out.println("Array after removing the element:");
for (int num : newArr) {
System.out.print(num + " ");
}
}
}
OUTPUT:
Array after removing the element:
10 20 40 50
Remove Element Using ArrayList
This program uses ArrayList
to dynamically remove an element with minimal effort and no manual resizing.
package com.javacodepoint.array;
import java.util.ArrayList;
public class RemoveElement2 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
// Remove element at index 2
list.remove(2);
// Print the updated list
System.out.println("ArrayList after removing the element: " + list);
}
}
OUTPUT:
ArrayList after removing the element: [10, 20, 40, 50]
Notes:
- The first method is suitable for fixed-size arrays but requires additional memory.
- The second method with
ArrayList
is easier and more efficient for dynamic collections.
Read Also: Add Element to Array in Java | Insert Element at Specific Position in Array.