How to Add and Remove an Element from an array at a Specific Index in Java

Share your love

As we know Arrays are a type of Data Structure that provides us a way to store a fixed number of elements of the same data type in a contiguous manner in our computer memory This makes it very hard to either add an element or remove an element from an array, as adding a new element will give us an out-of-bounds error from the compiler. While removal is still possible, if we did that, the original value will be replaced by a garbage value which in the case of int is 0.

Check some other garbage values that we can get for different data types.

Data TypeGarbage Value
Int / short / long0
Boolean False 
Double / float0.0
String Null 

See the image below

So how to solve it? There are many ways of doing that and among them, we will be discussing only 3 of them in this blog.

Let’s start…

Index 

  1. Creating a New Array of Required lengths – Brute Force Approach
  2. Using the System.arraycopy Method
  3. Using ArrayList

Creating a new array of required lengths – Brute Force Approach

Among the three approaches told above, this is the simplest and the basic approach to this problem. In this approach, we will create two new arrays of length one less or more than the length of the original array depending upon whether we are adding or removing an element.

Approach for adding a new element

  1. Create a new array of size n+1, where n is the size of the original array.
  2. Copy the elements of the original array to the new array before the given index where we have to add the new element.
  3. Add the new element to the given index.
  4. Copy the rest of the array with the i+1 index, where i is the index of the original array.
  5. Print it.
adding an element in an array
adding an element in an array

Below is the implementation of the above approach.

package com.Tekolio.Arrays;
 
import java.util.Arrays;
 
public class Adding_And_Removing_Elements {
    public static void main(String[] args) {
        //Original Array
        int[] A = {10, 20, 30, 40, 50, 60} ;
        System.out.print("Original Array : ");
        System.out.print(Arrays.toString(A));
        //size of the index
        int n = A.length;
        //Index at which the element will either be removed or added
        int p = 2;
        int x = 90;         // value to be added at index p
       
        int[] B = new int[n+1];// new array of the size 1 less than the original array

We are given an array A in which we have to add an element x=90 at the index p=2 and as told arrays are mutable and adding an element in the same array will give us an out-of-bounds error. Thus we have created a new array of n+1 size and copied all the elements before and after the given index from the original array in it and added the new element at the given index with the help of a for loop as shown below.

i<n+1; i++) {
    if(i<p) {
        B[i] = A[i];// copying all the elements before p
    }else if(i == p) {
        B[i] = x;// adding the new element at p
    }else{
        B[i] = A[i-1];// copying all the element with 1+ index
    }
}
System.out.print("Final Array : " + Arrays.toString(B));

As we have to add the given element at the 2nd index, we will copy all the elements before it i.e from indexes 0 and 1, and paste them into the new array.

At the second index of the array B, add the element x and copy the rest of the elements as it is but with an index of i+1 where i is the index of the original array and paste them into the new array. 

Output

Original Array : [10, 20, 30, 40, 50, 60]

Final Array : [10, 20, 90, 30, 40, 50, 60]

Approach for Removing an element from the given index

  1. Create a new array of size n-1, where n is the size of the original array.
  2. Copy the elements of the original array to the new array before the given index.
  3. Remove the element 
  4. Copy the rest of the array with the i-1 index, where i is the index of the original array.
  5. Print the new array
Remove an Element from an array
Remove an element from an array
package com.Tekolio.Arrays;
 
import java.util.Arrays;
 
public class Adding_And_Removing_Elements {
    public static void main(String[] args) {
        //Original Array
        int[] A = {10, 20, 30, 40, 50, 60} ;
        System.out.print("Original Array : ");
        System.out.print(Arrays.toString(A));
        //size of the index
        int n = A.length;
        //Index at which the element will either be removed or added
        int p = 2;
         
        int[] C = new int[n-1];// new array of the size 1 less than the original array
  for(int i=0; i<n; i++) {
            if(i < p) {
                C[i] = A[i];// copying all the elements before p
            }else {
                C[i-1] = A[i]; // copying the rest of the elements at index 1 less than the original
            }
        }
  System.out.print("Final Array : " + Arrays.toString(C));

The Array and the index p remain unchanged but rather than adding a new element we have to remove an element at the index p from the original array. 

The process also remains the same, the only difference is rather than copying the elements from the original array and pasting them at an index of i+1 in the new array, they will be pasted on index i-1 as the element at index p has to be removed.

Output

Original Array : 10,20,30,40,50,60

Final Array : 10,30,40,50,60

Using the System.arraycopy method

The System class in Java is a part of the lang package and comes with many different fields and methods, and systems. arraycopy() is among them. It is mainly used to copy the elements of an array into a new array, but in this, we have the liberty to decide how much and from where we want to copy elements and up to which index.

See the image below to understand it better

System.arraycopy method
System. arraycopy method

Syntax

System.arraycopy(source_array, source_index, dest_array, dest_index, length)

Where – 

source_arr: the original array

source_index: start index in source array from where to copy

dest_arr: array to be copied in

dest_index: start index in destination array, where to copy in

length: total no. of components to be copied.

Approach for adding a new Element

  1. Get the array and the index – p
  2. Create a new array of size one more than the size of the original array.
  3. Copy the elements from starting till p from the original array to the other array using System. arraycopy().
  4. At p, add the element in the new Array which has the size of 1 more than the actual array
  5. Copy the elements from index p of the original array and paste them from index p+1 in the new array till the end using System. arraycopy().
  6. Print the new array

Below is the implementation of the above approach.

package com.Tekolio.Arrays;
 
import java.lang.System;
import java.util.Arrays;
import java.util.Scanner;
 
public class Adding_an_Element {
    public static void main(String[] args)
    {
        // Original Array
        int[] A = { 10, 20, 30, 40, 50, 60 };
        System.out.print("Original Array : ");
        System.out.print(Arrays.toString(A));
        // size of the index
        int n = A.length;
        // Index at which the element be added
        int p = 2;
       // element that needs to be added
        int x = 100;
      // new Array of size +1 of the original array
        int[] B = new int[n + 1];
     
      // Copy the elements from starting till index
      // from original array to the other array
        System.arraycopy(A, 0, B, 0, p);
     
      // Copy the elements from p till end from original array
      // and paste it into the new array on p+1 index
        System.arraycopy(A, p, B, p + 1, n - p);
     
      // putting the element x on the index p of the new array
        B[p] = x;
     
      //Printing the new Array
      System.out.println();
        System.out.print("New Array : " + Arrays.toString(B));
    }
}

Output

Original Array : [10, 20, 30, 40, 50, 60]

New Array : [10, 20, 100, 30, 40, 50, 60]

In the above code, all the variables remain the same like the array A, the element to be added x, and the index at which it will be added p. The only difference is that this time we are not using any loop to copy all the elements and add the new one at the specified index. 

Rather, we are using the System. arraycopy() method of the System class of Java lang Package which allows us to copy elements of the array without using any loop but the fact that we have to make a new array with a size greater than the original remains unchanged.

System.arraycopy(A, 0, B, 0, p);
System.arraycopy(A, p, B, p + 1, n - p);
B[p] = x;

In the above code, we have first copied the original array from index 0 and pasted it to the new array at index 0 till p-1, then we have again copied the rest of the elements from the p position from the original array and pasted it at p+1 position in the entire array leaving us with the position p at which we have added the new element.

Approach for Removing an element for an index

  1. Get the array and the index p.
  2. Create a new array of size one less than the size of the original array.
  3. Copy the elements from starting till index from the original array to the other array using System. arraycopy().
  4. Copy the elements from index + 1 till the end from the original array to the other array using System. arraycopy().
  5. Print the array.
package com.Tekolio.Arrays;
 
import java.lang.System;
import java.util.Arrays;
import java.util.Scanner;
 
public class Adding_an_Element {
    public static void main(String[] args)
    {
        // Original Array
        int[] A = { 1, 2, 3, 4, 5, 6 };
        System.out.print("Original Array : ");
        System.out.print(Arrays.toString(A));
        // size of the index
        int n = A.length;
        // Index at which the element be added
        int p = 2;
      // new Array of size +1 of the original array
        int[] B = new int[n - 1];
     
      // Copy the elements from starting till index
      // from original array to the other array
        System.arraycopy(A, 0, B, 0, p);
     
       // Copy the elements from index + 1 till end
        // from original array to the other array
        System.arraycopy(A, p+1, B, p, n-p-1);
     
      //Printing the new Array
      System.out.println();
        System.out.print("New Array : " + Arrays.toString(B));
    }
}

Output

Original Array : [10, 20, 30, 40, 50, 60]

New Array : [10, 20, 40, 50, 60]

The process for removing an element from the array is the same as adding a new element, the only difference is that in this the new array will be of size 1 less than the original array and while copying the elements from the original array after p, the element at the position will not be considered while copying the array and the copying will start from p+1 of the original array and will be posted at index p of the new array.

Method 3 – Using the Arraylist

ArrayList is a part of the collection framework and is present in java. util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.

But unlike Array, it is resizeable meaning its size is not fixed and adjusts itself according to the size of the array. Thus no need to create a new array of sizes n+1 and n-1 to add and remove an element. Just by using some of its methods, we can achieve that very easily.

Approach for Adding a New Element in the Array

  1. Create an ArrayList with Integer Wrapper class
  2. Copy all the elements from the original array into the ArrayList using for each loop.
  3. Add the element using the add() method
  4. Convert the ArrayList back into an array 
  5. Print the Array

Below is the implementation of the above Approach

package com.Tekolio.Arrays;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
 
public class practice {
    public static void main(String[] args) {
        //Original Array
        int[] A = {10, 20, 30, 40, 50, 60} ;
        System.out.print("Original Array : " + Arrays.toString(A));
        //size of the index
        int n = A.length;
        //Index at which the element will either be removed or added
        int p = 2;    
        int x = 90;
        // Creating a new ArrayList with Integer Wrapper Class
        ArrayList<Integer> F = new ArrayList<>();
        //copy all the elements from A to F
        for(int i:A) {
            F.add(i);
        }
        //add the element x at p
        F.add(p, x);
        //Convert the ArrayList back into Array        
        int[] G = F.stream().mapToInt(i->i).toArray();
        //Print the array
        System.out.print("Final Array : " + Arrays.toString(G));
 }
}

Output

Original Array : [10, 20, 30, 40, 50, 60]

Final Array : [10, 20, 90, 30, 40, 50, 60]

The process is the same as the methods we have used above, the only difference is that we have used an ArrayList and avoided the size issue that we were facing in the above methods.

We have first created an ArrayList and then with the help of forEach loop copied all the elements from the int Array A into the newly formed ArrayList, and with the help of the add() method provided to us by the ArrayList, we added the element x at the index p.

The trickier part is to convert this ArrayList back into an Array as we have to return/print an array. We have done this using the Streams method of Java and the MapPoint method of Streams.

 int[] G = F.stream().mapToInt(i->i).toArray();

The point method of the streams is used to map each item from a stream to an int which converts the Integer or any wrapper class to its primitive data type, formed in this chase int.

Approach for Removing an Element from the array

  1. Create an ArrayList with Integer Wrapper class
  2. Copy all the elements from the original array into the ArrayList using for each loop.
  3. Remove the element using the remove() method
  4. Convert the ArrayList back into an array 
  5. Print the Array
package com.Tekolio.Arrays;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
 
public class practice {
    public static void main(String[] args) {
        //Original Array
        int[] A = {10, 20, 30, 40, 50, 60} ;
        System.out.print("Original Array : " + Arrays.toString(A));
        //size of the index
        int n = A.length;
        //Index at which the element will either be removed or added
        int p = 2;    
        // Creating a new ArrayList with Integer Wrapper Class
        ArrayList<Integer> H = new ArrayList<>();
        // copy all the elements from A to H
        for(int i:A) {
            H.add(i);
        }
        // remove the element from index p
        H.remove(p);
        // convert ArrayList back into Array
        int[] I = H.stream().mapToInt(i->i).toArray();
        // Print the Array
        System.out.print("Final Array : " + Arrays.toString(I));
    }
}

Output

Original Array : [10, 20, 30, 40, 50, 60]

Final Array : [10, 20, 40, 50, 60]

The process remains the same as when we were adding a new element in the array the only difference is despite adding, we are removing an element from the original array at the index p using the remove() method of ArrayList

The process used above is Autoboxing and Unboxing in which we convert a primitive data type into its wrapper class and vice versa respectively. To get a better understanding of these processes, read the official documentation.

Conclusion

There are numerous ways to add or remove an element from an array at a specified index and we have discussed three such ways in this blog.

We can just add and remove an element from an array as arrays are mutable and have sizes and increasing and decreasing that is not possible thus to add and remove an element we need a new array with either n+1 size or n-1 size depending upon which operations we are doing adding or removing and where n is the size of the original array. 

But this process is a beginner’s approach and requires brute force which is necessary to understand the problem and how to solve it so that we can come up with a way to optimize it ahead.

And at the very end, we have solved this problem with the help of an ArrayList which is considered the most efficient approach in that we are first converting the array into ArrayList with the process called autoboxing and then converting it back into an array with a process called unboxing.

There can be way more approaches using the same tricks or methods which we have used but we have found these three to be quite easy to understand and that’s why we are discussing them.

Frequently Asked Questions

How to add new elements in an array in Java

  1. By creating a new array of size n+1, where n is the size of the original array, and copying everything in this array with the new element added as well.
  2. By using the ArrayList’s add method.

How to remove an element from an array in java

  1. By creating a new array of size n-1, where n is the size of the original array, and copying everything in this array without the element which needs to be removed
  2. By using the ArrayList’s add method.

Can we increase the size of an array in java

 No, We cannot increase the size of the array in Java once it is instantiated as arrays are mutable. But we can create an array of a size greater than the original array and move all the elements to it.

How to convert an ArrList back into an Array in Java

 No, We cannot increase the size of the array in Java once it is instantiated as arrays are mutable. But we can create an array of a size greater than the original array and move all the elements to it.

What are Growable Arrays in Java

A growable array is simply a dynamic array that increases its size when more items are added to it. In Java, it is known as ArrayList

Share your love