Writing a Java program to remove element from an array may look like a simple task but it comes with its own set of problems. Those problems stem from the fact that array in Java is fixed in length. Which means you can't just remove an element from the given index in an array, you will need to shift all the elements that are after the element that has to be removed, to the left to fill the gap left by the removed element.
Once the element are shifted to fill the gap that leaves space at the end of the array (remember array size is fixed). Array size will not reduce after removing the element and the element that is at the end will be repeated to fill the empty space.
Let's try to clarify it with an example-
Here the array removal is done without using any third party tool (like Apache common utils) or any data structure provided
by the Java language (Like Collection classes).
So the steps followed to remove element from an array are-
- Ask the user to enter the element to be removed.
- Search in the array for the given element.
- If found shift all the element after that index to the left by one element. As example if element to be deleted is
at index i then remove all the elements from index i+1 to array.length by one element which means element at i+1 will
come at index i.
Java program to remove element from an array
import java.util.Scanner;
public class ElemRemoval {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] intArr = {1, 2, 5, 12, 7, 3, 8};
System.out.print("Enter Element to be deleted : ");
int elem = in.nextInt();
for(int i = 0; i < intArr.length; i++){
if(intArr[i] == elem){
// shifting elements
for(int j = i; j < intArr.length - 1; j++){
intArr[j] = intArr[j+1];
}
break;
}
}
System.out.println("Elements -- " );
for(int i = 0; i < intArr.length; i++){
System.out.print(" " + intArr[i]);
}
}
}
Output
Enter Element to be deleted : 5
Elements --
1 2 12 7 3 8 8
If you notice last element 8 is repeated to fill the space that is left after shifting the elements.
Now when you have basic idea about the scenarios that you need to take care of while removing element from an array let's see what all alternatives are there to do that.
Using new array
When you remove an element from an array, you can fill the empty space with 0, space or null depending on whether it is
a primitive array, string array or an Object array.
Other alternative is to create a new array and copy the elements in that array. New array should have size of old
array’s size – 1.
Let’s see an example where new array is used-
import java.util.Scanner;
public class ElemRemoval {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] intArr = {1, 2, 5, 12, 7, 3, 8};
int[] newArr = null;
System.out.print("Enter Element to be deleted : ");
int elem = in.nextInt();
/*for(int i = 0; i < intArr.length; i++){
if(intArr[i] == elem){
for(int j = i; j < intArr.length - 1; j++){
intArr[j] = intArr[j+1];
}
break;
}
}*/
for(int i = 0; i < intArr.length; i++){
if(intArr[i] == elem){
newArr = new int[intArr.length - 1];
for(int index = 0; index < i; index++){
newArr[index] = intArr[index];
}
for(int j = i; j < intArr.length - 1; j++){
newArr[j] = intArr[j+1];
}
break;
}
}
System.out.println("Elements -- " );
for(int i = 0; i < newArr.length; i++){
System.out.print(" " + newArr[i]);
}
}
}
Output
Enter Element to be deleted :
5
Elements --
1 2 12 7 3 8
Enter Element to be deleted : 8
Elements --
1 2 5 12 7 3
With copying the element to the new array problem of empty space is solved.
Using ArrayUtils to remove element from an array
If you can use Apache commons in your application then there is a utility class ArrayUtils that can be used to remove elements from an array.
import java.util.Scanner;
import org.apache.commons.lang3.ArrayUtils;
public class ElemRemoval {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] intArr = {1, 2, 5, 12, 7, 3, 8};
System.out.print("Enter Element to be deleted : ");
int elem = in.nextInt();
for(int i = 0; i < intArr.length; i++){
if(intArr[i] == elem){
// Using ArrayUtils
intArr = ArrayUtils.remove(intArr, i);
break;
}
}
System.out.println("Elements -- " );
for(int i = 0; i < intArr.length; i++){
System.out.print(" " + intArr[i]);
}
}
}
Output
Enter Element to be deleted : 2
Elements --
1 5 12 7 3 8
Using System.arraycopy() method to remove element from an array
Description of the System.arraycopy method
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) - Copies an array from the specified source array,
beginning at the specified position, to the specified position of the destination array. A subsequence of array components
are copied from the source array referenced by src to the destination array referenced by dest. The number of components
copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are
copied into positions destPos through destPos+length-1, respectively, of the destination array.
If you use the same array as source and destination you will have the same issue of repeating element as discussed in
the first program as the array length is fixed. In the example code new array is used as destination.
import java.util.Arrays;
import java.util.Scanner;
public class ElemRemoval {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] intArr = {1, 2, 5, 12, 7, 3, 8};
System.out.print("Enter Element to be deleted : ");
int elem = in.nextInt();
for(int i = 0; i < intArr.length; i++){
if(intArr[i] == elem){
removeElement(intArr, i);
break;
}
}
}
public static void removeElement( int [] arr, int index ){
// Destination array
int[] arrOut = new int[arr.length - 1];
int remainingElements = arr.length - ( index + 1 );
// copying elements that come before the index that has to be removed
System.arraycopy(arr, 0, arrOut, 0, index);
// copying elements that come after the index that has to be removed
System.arraycopy(arr, index + 1, arrOut, index, remainingElements);
System.out.println("Elements -- " + Arrays.toString(arrOut));
}
}
Output
Enter Element to be deleted : 5
Elements -- [1, 2, 12, 7, 3, 8]
Using ArrayList to remove element from an array
If you want to remove element from an array using Collection API provided by the Java language then you can convert array to an ArrayList and then remove element from the ArrayList. Shuffling and all would be taken care of by the ArrayList itself. Once the element is removed you
can again
convert the ArrayList to an array.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class ElemRemoval {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Integer[] intArr = {1, 2, 5, 12, 7, 3, 8};
System.out.print("Enter Element to be deleted : ");
int elem = in.nextInt();
System.out.println("Original Array " + Arrays.toString(intArr));
for(int i = 0; i < intArr.length; i++){
if(intArr[i] == elem){
intArr = removeElementUsingCollection(intArr, i);
break;
}
}
System.out.println("Array after removal of Element -- " );
for(int i = 0; i < intArr.length; i++){
System.out.print(" " + intArr[i]);
}
public static Integer[] removeElementUsingCollection( Integer[] arr, int index ){
List<Integer> tempList = new ArrayList<Integer>(Arrays.asList(arr));
tempList.remove(index);
return tempList.toArray(new Integer[0]);
}
}
Output
Enter Element to be deleted : 2
Original Array [1, 2, 5, 12, 7, 3, 8]
Array after removal of Element --
1 5 12 7 3 8
That's all for this topic How to Remove Elements From an Array Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
-
Find Duplicate Elements in an Array Java Program
-
Remove Duplicate Elements From an Array in Java
-
Matrix Subtraction Java Program
-
Difference Between Array And ArrayList in Java
-
How ArrayList Works Internally in Java
You may also like-
-
Split a String Java Program
-
Format Date in Java Using SimpleDateFormat
-
How to Create PDF From XML Using Apache FOP
-
How to Create Deadlock in Java
-
Difference Between equals() Method And equality Operator == in Java
-
Arithmetic and Unary Operators in Java
-
Java Object Cloning - clone() Method
-
Java Nested Class And Inner Class