Add elements to Array in Java
An array is the collection of similar types of elements stored at contiguous locations in the memory. The main advantage of an array is that we can randomly access the array elements, whereas the elements of a linked list cannot be randomly accessed.
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. Let's suppose we have an array arr, and we need to add elements to it. We can use the following methods to add elements to arr.
Let's have an inside look into the ways we have described.
Creating a larger size array
To add elements in the java array, we can create another larger size array and copy all elements from our array to another array and place the new value at the last of the newly created array. However, it is not an efficient way to add an element to the array. In the below example, An element 7 is added to the array arr with the help of a newly created array newArr. Consider the following example.
We can use ArrayList as the intermediate structure and add the elements into the ArrayList using the add () method. ArrayList is a data structure that allows us to dynamically add elements. However, we can convert the ArrayList to the array by using the toArray() method. Hence this process involves the following steps.
Consider the following example.
Array:[1, 2, 3, 4, 5, 6] Array after adding element: [1, 2, 3, 4, 5, 6, 7]
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.
In this method, we will,
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.
Original Array: [1, 2, 3, 4, 5, 6] Array after adding value: [1, 2, 3, 7, 4, 5, 6]
Next TopicAdvantages and disadvantages of Java