Add Elements to Array in Java

In Java, arrays are basic data structures for storing elements of the same type in consecutive memory locations. Although arrays have a fixed size once they are created, there are different ways to add elements or create new arrays with new elements In this section, we will explore different ways adding elements to an array in Java.

An array is a collection of identical objects stored in consecutive locations in memory. The main advantage of an array is that we can randomly access the items in an array, whereas the elements in a linked list cannot be randomly moved.

In Java, Arrays are mutable data types, i.e., the size of the array is fixed, and we cannot directly add a new element in Array. However, there are various ways to add elements to the array.

Using ArrayList

Java's ArrayList is a dynamic array implementation that generates resizable arrays. It belongs to the Java Collections Framework and provides ways to add objects dynamically. Here's how we can use ArrayList to add elements to an array-like structure:

File Name: UsingArrayList.java

Output:

10
20
30

Using Arrays.copyOf()

The arrays.copyOf() method in Java allows us to copy an existing array into a new array of specified length. We can add elements to the original array and assign additional lengths.

File Name: UsingArrayscopyOf.java

Output:

1
2
3
4
5
6
7
8

Using System.arraycopy() Method

The Java System.arraycopy() method is used to copy data from one array to another. We can use this method to create new layouts with additional features.

File Name: Systemarraycopy.java

Output:

1
2
3
4
5
6
7
8

Shifting elements to adjust the size of the array

In this method, we will add the elements to the specified index in the array. Likewise, the above two processes will use a new destination array with a larger size than the original array. However, it will be tricky to shift the destination array elements after copying all elements from the original array to destination array.

We will follow the steps given below to add element in the array:

  1. Create a new destination array with a larger size than the original array.
  2. Copy all the elements from the original array to the new destination array
  3. Shift the elements after the given index to the right until it reaches the end of the array.
  4. Insert the new element at the given index.

Consider the following example in which we will add a specific value at the given index 3 in the original array using a destination array.

File Name: JavaAddElementArraySpecified.java

Output:

Original Array: [1, 2, 3, 4, 5, 6]
Array after adding value: [1, 2, 3, 7, 4, 5, 6]

Conclusion

In Java, elements can be added to an array using various methods such as ArrayList, Arrays.copyOf(), and System.arraycopy(). The advantages of each option depend on the specific requirements of your application. Understanding these techniques allows us to manipulate arrays in Java programs.