Monday, 10 July 2017

How to remove elements from an array - Java Program

Removing 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, left by one element.

Also the array size will still not reduce 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 to remove the elements, followed in the code are -

  1. Ask the user to enter the element to be removed.
  2. Search in the array for the given element.
  3. 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){
                
                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.

Alternatives

You can fill the empty space with 0, space or null depending on whether it is 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.

Example code

 
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.

Example code

 
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 Collection classes

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. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Finding duplicate elements in an array - Java Program
  2. How to remove duplicate elements from an array - Java Program
  3. Matrix Subtraction - Java Program
  4. Difference between Array and ArrayList in Java
  5. How ArrayList works internally in Java

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment