how to add an element to an array java
Oh, Java arrays. They are the object of intense love and hatred of hundreds of beginner software developers. Adding elements to an array that was already initialised is impossible, they said… Actually, it is possible, but not in a classical meaning… and it isn't very convenient. Adding new elements to an array that was already initialised is a kind of a trick. However, these tricks can come in handy in an interview ... and sometimes in a programmer's job. To make sure you enjoy using the data type and know how to do it efficiently, we wrote a guide on adding a new element to a Java array. Other than carefully going through the theory and code samples, be sure to check out and complete the practice problems featured in the post.
What is an Array in Java
Let's recall what an Array is and how to create it in Java. If you remember that, feel free to skip ahead to the next subheading "5 Ways to Add New Elements to Java Arrays". Oracle's official Java documentation says that arrays are a series of values belonging to the same data type. A set of integers is a perfect example of an array in Java. All values you define have a specific position within the array called an index. Here are the ways to declare and initialize arrays:
int[] myArray = new int[10]; int[] myArray1 = {1, 0, 3, 17, 5, 6, 7, 8, 9, 10}
In the first case, we defined an array myArray and made Java to allocate space for an array of 10 elements, in the second myArray1, we immediately entered 10 values into it. In either case, element 11 cannot be simply pushed into the array. To perform operations with arrays, developers manipulate the indices of values an array contains. What should we do? Let's take a look at the most common ways to add to array.
5 Ways to Add New Elements to Java Arrays
Well, here our tricks to make the immutable seem mutable.
- Convert an Array to a List
- Create a new array with larger capacity and add a new element to the array
- Implementing System.arraycopy()
- Copying arrays using Apache Commons
- Applying the ArrayCopyOf() method
Let's take a closer look at these ways to add an element to an array.
1. Converting an Array to a List
Since we can't add a new element to an array directly, the next best thing to do is to convert them to lists, add new elements, and reconvert the values back to arrays. The first way to convert an array to a list is to use asList() to create a new ArrayList. Once the range of values is successfully transformed, use ListAdd() to insert the value. Once you no longer need to edit an array, convert back to the original data type with the help of toArray() method. With all the methods and conversions, this can seem confusing at first. Let's take a look at the example of using asList() to clear things up.
// Code for adding Java arrays to a program import java.lang.*; import java.util.*; class ArrayDemo{ //Let's add a new element to an array public static Integer[] addX(Integer myArray[], int x) { int i; //turn array into ArrayList using asList() method List arrList = new ArrayList( Arrays.asList(myArray)); // adding a new element to the array arrList.add(x); // Transforming the ArrayList into an array myArray = arrList.toArray(myArray); return myArray; } public static void main(String[] args) { int i; //initial array Integer myArray[] = { 0, 1, 2, 45, 7, 5, 17}; //print the initial array out System.out.println("Initial Array: " + Arrays.toString(myArray)); //element to be added int x = 28; // call the method to add x in myArray myArray = addX(myArray, x); // print the updated array out System.out.println("Array with " + x + " added: " + Arrays.toString(myArray)); } }
The output is:
Initial Array: [0, 1, 2, 45, 7, 5, 17] Array with 28 added: [0, 1, 2, 45, 7, 5, 17, 28]
So, in the program we have successfully created an array myArray of 7 values, filled it in and printed it out. Then we decided that ten values were not enough for us. Well, we converted myArray to an ArrayList arrList using the Arrays.asList method. Here is 28, the element to be added. We added it to the ArrayList arrList, and then converted it back to an array using the toArray() method and printed out the new array.
2. Create a new array with a larger capacity
One of the most common ways to add more elements to an array is by creating a new, larger, array from scratch, putting the elements of the old ones and adding new elements. Here's a step-by-step walkthrough of the process:
- Create a new array with the capacity a+n (a — the original array capacity, n — the number of elements you want to add).
- Add all the elements of the previous data range to the new one, as well as the new values.
- Print the resulting array.
Try creating such an array on your own and compare your code to that in the example below:
// Java Program to add an element in an Array import java.lang.*; import java.util.*; class ArrayDemo { //Method to add an element x into array myArray public static int[] addX(int myArray[], int x) { int i; // create a new array of a bigger size (+ one element) int newArray[] = new int[myArray.length + 1]; // insert the elements from the old array into the new one for (i = 0; i < myArray.length; i++) newArray[i] = myArray[i]; newArray[myArray.length] = x; return newArray; } public static void main(String[] args) { int i; // initial array of size 10 int arr[] = {0, 1, 2, 45, 7, 5, 17}; // print the initial array System.out.println("Initial Array: " + Arrays.toString(arr)); // element to be added int x = 28; // call the addX method to add x in arr arr = addX(arr, x); // print the updated array System.out.println("Array with " + x + " added:" + Arrays.toString(arr)); } }
The output is:
Initial Array: [0, 1, 2, 45, 7, 5, 17] Array with 28 added:[0, 1, 2, 45, 7, 5, 17, 28]
Well, this way to add a new element into an array is the easiest one.
3. Applying System.arrayCopy()
System.arrayCopy() is a widely used method for allocating a larger array at the destination of a source array. A developer can specify the sequence he wants to copy to a new array in the brackets of the method. To see how the method works and try using it for yourself, take a look at and try running the example below:
import java.util.Arrays; class ArrayDemo { private static Integer[] addElement(Integer[] myArray, int newElement) { //we create a new Object here, an array of bigger capacity Integer[] array = new Integer[myArray.length + 1]; System.arraycopy(myArray, 0, array, 0, myArray.length); array[myArray.length] = newElement; return array; } public static void main(String[] args) { Integer[] myArray = {20, 21, 3, 4, 5, 88}; System.out.println("myArray before adding a new element: " + Arrays.toString(myArray)); myArray = addElement(myArray, 12); System.out.println("myArray before adding a new element: " + Arrays.toString(myArray)); } }
The output is:
myArray before adding a new element: [20, 21, 3, 4, 5, 88] myArray before adding a new element: [20, 21, 3, 4, 5, 88, 12]
Here we have created an array myArray, printed it out and added a new element using our addElement method, which is built on System.arrayCopy().
4. Using Apache Commons to copy arrays
Let's use a non-standard way. Namely, a third-party library Apache Commons lang. It is a part of Apache Commons project focused on all aspects of reusable Java components. Knowledge about the project will not be superfluous. The Apache Commons lang has a method add() designed specifically to allow expanding arrays, it saves codders a lot of time and effort. It's worth keeping in mind that this Apache Commons add() method is based on calling System.arraycopy() method in case you have to answer a tricky exam or interview question. To add the libraries into your project go to Apache Commons website and download the libraries. Then go to the File → Project Structure → Libraries > + and select the downloaded jar files.
import org.apache.commons.lang3.ArrayUtils; import java.util.Arrays; class ArrayDemo { private static T[] append(T[] arr, T element) { return ArrayUtils.add(arr, element); } public static void main(String[] args) { Integer[] myArray = { 0, 1, 2, 3, 4}; System.out.println("myArray: " + Arrays.toString(myArray)); myArray = append(myArray, 5); System.out.println("new Array with the number added: " + Arrays.toString(myArray)); } }
The output is:
myArray: [0, 1, 2, 3, 4] new Array with the number added: [0, 1, 2, 3, 4, 5]
5. Implementing ArrayCopyOf()
ArrayCopyOf() is one more method to add a new element to an array. Such as Apache Commons lang add() it internally calls System.arraycopy() for doing this operation. However most developers prefer ArrayCopyOf() since it allows them to keep the code concise and readable. Here's an example of using ArrayCopyOf() to add new elements to an array:
import java.util.Arrays; class ArrayDemo { private static X[] addElement(X[] myArray, X element) { X[] array = Arrays.copyOf(myArray, myArray.length + 1); array[myArray.length] = element; return array; } public static void main(String[] args) { Integer[] myArray = {20, 21, 3, 4, 5, 88}; System.out.println("myArray before adding a new element: " + Arrays.toString(myArray)); myArray = addElement(myArray, 12); System.out.println("myArray before adding a new element: " + Arrays.toString(myArray)); } }
The output is:
myArray before adding a new element: [20, 21, 3, 4, 5, 88] myArray before adding a new element: [20, 21, 3, 4, 5, 88, 12]
Conclusion
Knowing how to add elements to an array helps developers update the old code quickly without sacrificing its functionality and readability… Or just to pass the interview. Since there are different ways to add elements to Java arrays, feel free to choose the method you are comfortable with.
how to add an element to an array java
Source: https://codegym.cc/groups/posts/add-new-element-to-array
Posted by: eppersonsuldatime.blogspot.com
0 Response to "how to add an element to an array java"
Post a Comment