Add Elements to Array and ArrayList in Java
An array is a fixed-size collection of similar objects in Java. An ArrayList is very similar to an array but has no size restrictions.
In this tutorial, we will learn how to insert elements in arrays and ArrayLists.
Difference Between Array and ArrayList
Before learning how to insert elements, let's first take a quick look at some of the differences between arrays and ArrayLists.
Implementation
An Array is a simple, linear data structure provided by Java. ArrayList is a class in Java that implements the List interface, and it is part of the Collections Framework. ArrayList internally uses an Array for its operations.
Accessing and Modifying Elements
Elements of an array are accessed and modified by using indexes. The ArrayList class provides getter and setter methods to access and modify its content.
Element Types
Arrays are capable of storing primitive as well as non-primitive types. ArrayLists can only store non-primitive types. However, we can use wrapper classes to store primitives.
Size
As discussed above, arrays are of fixed size, while ArrayLists have dynamic size. For an array, we need to define its size during instantiation. We cannot exceed this size limit. For ArrayLists, the size dynamically increases when we need to add more elements to it. A new underlying array of larger size is created to accommodate the additional items.
Appending Elements
Let's learn how to append elements to an array and ArrayList. Append means to add to the end.
Appending to Arrays
We will first create a new array of larger size. Next, we will transfer the elements to this new array. Finally, we can add the new item at the end of this new array. The following code demonstrates this.
import java.util.Arrays;
public class Demo
{
public static int[] appendToArray(int[] arr, int elementToAdd)
{
int[] newArr = new int[arr.length + 1];//new array of larger size
//copying elements from old to new array
for(int i = 0; i < arr.length; i++)
newArr[i] = arr[i];
newArr[newArr.length - 1] = elementToAdd;//Adding the element
return newArr;
}
public static void main(String[] args)
{
int[] arr = {1, 2, 3, 4, 5, 6};
System.out.println("Initial Array: " + Arrays.toString(arr));
arr = appendToArray(arr, 7);
arr = appendToArray(arr, 8);
arr = appendToArray(arr, 9);
System.out.println("After adding the element: " + Arrays.toString(arr));
}
}
Initial Array: [1, 2, 3, 4, 5, 6]
After adding the element: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The Arrays class provides a simple copyOf() method that copies the elements from the old array to the new one. This method takes the old array and the new array's size as parameters. Let's rewrite the above code by using the copyOf() method instead of a for loop.
import java.util.Arrays;
public class Demo
{
public static int[] appendToArray(int[] oldArr, int elementToAdd)
{
//creating a new array and copying the elements
int[] newArr = Arrays.copyOf(oldArr, oldArr.length + 1);
newArr[newArr.length - 1] = elementToAdd;
return newArr;
}
public static void main(String[] args)
{
int[] arr = {1, 2, 3, 4, 5, 6};
System.out.println("Initial Array: " + Arrays.toString(arr));
arr = appendToArray(arr, 7);
arr = appendToArray(arr, 8);
arr = appendToArray(arr, 9);
System.out.println("After adding the element: " + Arrays.toString(arr));
}
}
Initial Array: [1, 2, 3, 4, 5, 6]
After adding the element: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Appending to ArrayList
Appending to an ArrayList is pretty straightforward. This class comes with an add() method that adds an element to the end of the list. The following code demonstrates this.
import java.util.ArrayList;
public class Demo
{
public static void main(String[] args)
{
ArrayList<Integer> arrList = new ArrayList<>();
arrList.add(1);
arrList.add(2);
arrList.add(3);
System.out.println("ArrayList: " + arrList);
}
}
ArrayList: [1, 2, 3]
Inserting Elements
Let's now try to insert elements at any index. Make sure that the index is within the bounds to avoid the IndexOutOfBoundsException. We will
Inserting in an Array
First, we will create a new array to accommodate the additional element. To insert at a given index, we need to shift the element present at that index and all elements after this index one place to the right.
For example, consider the initial array [10, 20, 30, 40], and we need to insert 50 at index 1. The elements 20, 30, and 40 will shift one place to the right. The resulting array will be [10, 50, 20, 30, 40].
import java.util.Arrays;
public class Demo
{
public static int[] insertAtIndex(int[] arr, int elementToAdd, int index)
{
int[] newArr = new int[arr.length + 1];//new array of larger size
//Copying and adding the new element
int currIdx = 0;
for(int i = 0; i < newArr.length; i++)
{
if(i == index)
newArr[i] = elementToAdd;
else {
newArr[i] = arr[currIdx];
currIdx += 1;
}
}
return newArr;
}
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40};
System.out.println("Initial Array: " + Arrays.toString(arr));
arr = insertAtIndex(arr, 50, 1);
System.out.println("After adding 50 at index 1: " + Arrays.toString(arr));
}
}
Initial Array: [10, 20, 30, 40]
After adding 50 at index 1: [10, 50, 20, 30, 40]
Inserting in an ArrayList
The add() method has an overloaded version which also takes the index where we want to add an element. The items are moved from one place to the right to make space for the new item.
import java.util.ArrayList;
public class Demo
{
public static void main(String[] args)
{
ArrayList<Integer> arrList = new ArrayList<>();
arrList.add(10);
arrList.add(20);
arrList.add(30);
arrList.add(40);
System.out.println("Initial ArrayList: " + arrList);
arrList.add(1, 50);
System.out.print("After adding 50 at index 1: " + arrList);
}
}
Initial ArrayList: [10, 20, 30, 40]
After adding 50 at index 1: [10, 50, 20, 30, 40]
Summary
Inserting elements in an array is quite complicated. We need to create a new array and transfer the contents of the old one. However, an ArrayList provides a convenient add() method to append or insert elements. Make sure to a valid index to avoid an index-out-of-bounds error. Note that the add() method has a worst-case time complexity of O(N). It is because of the creation of a new underlying array.