In this article, we will discuss how to add elements to Array in Java with different methods. We will discuss 3 ways to add elements to an array in java.
What is Array?
An array is a collection of similar data types stored at contiguous memory locations. Data elements can be accessed using their index number. It is the simplest data structure.
The fundamental benefit of an array is that we can randomly get to the array elements, though the elements of a connected rundown can’t be randomly gotten to.
For example, if we want to store the marks scored by a student in 10 subjects, then we can define an array that will store the data elements at contiguous memory locations. There’s no need to define individual variables for each subject.
Structure of Array
array marks[9]
The above code will define the array in which we can store 10 different subjects scores. marks[0] denotes the marks scored in the first subject, marks[1] denotes the marks scored in 2nd subject, and so on.
In Java, the array length is fixed, and we cannot instantly add a new element to the Array. Basically, there are 3 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 ways to add elements to array in Java.
Let’s have a profound investigation of the ways we have described.
1. Creating a larger size array
In Java, we can create a new large array and copy elements from the old Array. Copy elements from the old Array to another new Array and add the new value at the last of the newly created Array. It is not an efficient way to add an element to the array.
2. Using ArrayList
- Convert Array into ArrayList using asList() method.
- Add elements into the array list using the add() method.
- Convert the ArrayList again to the array using the toArray() method.
3. Shifting elements to adjust the size of the array
- Create a new destination array with a larger size than the original array.
- Copy all the elements from the original array to the new destination array
- Shift the elements after the given index to the right until it reaches the end of the array.
- Insert the new element at the given index.