Low Orbit Flux Logo 2 D

Java How To Add / Append To An Array

Adding an element to an array is easy in Java. We’re going to show you how to do this. It is not as easy as in other languages but it still isn’t a big deal. Expanding an array beyond its original size is generally going to be inefficient.

Quick Answer:

int array1[] = {1,2,3,4,5,6,7,8,9,10};  
int array2[] = new int[array1.length + 1];
for (int i = 0; i < n; i++)
    array2[i] = arr[i]; 
array2[n] = x;

There are a few different methods that you could use. Keep reading for more details on these.

Create a New, Bigger Array

The idea with this method is to do the following:

import java.util.Arrays;  

public class Test1 {  
    public static void main(String[] args) { 
        int x = 25;     // new value to add
        int array1[] = {1,2,3,4,5,6,7,8,9,10};  
        int n = array1.length; 
        int array2[] = new int[n + 1];

        for (int i = 0; i < n; i++)
            array2[i] = array1[i]; 
        array2[n] = x;

        System.out.println(Arrays.toString(array1)); 
        System.out.println(Arrays.toString(array2)); 
    }
}

Adding an Element to the Middle of an Array

If you want to add an element to the middle of an array while keeping all of the other elements in place it will take a bit more effort. The main idea with this is that you will want to expand the size of the array while adding a new element to any arbitrary index that you choose.

import java.util.Arrays;  
  
public class Test1 {  
    public static void main(String[] args) {  
        int array1[] = {1,2,3,4,5,6,7,8,9,10};  
        int n = array1.length;  
        int array2[] = new int[n+1]; 
        int x = 3;                             // index to insert
        int value = 25;                    // value to insert
 
        int j = 0;  
        for( int i = 0; i < array2.length; i++ ) {  
            if( i == x ) {  
                array2[i] = value;  
            }
            else {  
                array2[i] = array1[j];  
                j++;  
            }  
        }  
        array2[x] = value;    

        System.out.println(Arrays.toString(array1));  
        System.out.println(Arrays.toString(array2));  
    }  
}

ArrayList

You can use an ArrayList as replacement for an array. You can also use it as a structure to expand the array before writing it back to the original. Here is how you would do that.

import java.util.ArrayList;  
import java.util.Arrays;  
public class Test1 {  
    public static void main(String[] args) {  
        Integer array1[] = {1,2,3,4,5,6,7,8,9,10};  
        System.out.println(Arrays.toString(array1)); 
        ArrayList<Integer> array2 = new ArrayList<Integer>(Arrays.asList(array1));  
        array2.add(25);  
        array1 = array2.toArray(array1);  
        System.out.println(Arrays.toString(array1)); 
    }   
}