In this post, we will see how to add elements to the Array.
Using Apache’s common lang library
You can use varargs add method to add elements to array dynamically.
Here are the few add overloaded methods provided by ArrayUtils class
If you want to add more than one element, you can use ArrayUtils’s addAll methods.
Here is quick example using ArrayUtil’s add method
package org.arpit.java2blog; import java.util.Arrays; import org.apache.commons.lang3.ArrayUtils; public class JavaAddToArrayMain { public static void main(String args[]) { int[] arr= {1,2,3}; int[] arrToBeAdded= {4,5}; int[] appendedArray=ArrayUtils.addAll(arr, arrToBeAdded); for (int i = 0; iWhen you run above program, you will get below output.
1 2 3 4 5By writing your own utility method
As Array is fixed in length, there is no direct method to add elements to the array, you can write your own utility method.
We have used varargs here to support n numbers of elements that can be added to array.package org.arpit.java2blog; import java.util.Arrays; public class JavaAddToArrayMain { public static void main(String args[]) { Object[] arr= {1,2,3}; Object[] arrToBeAdded= {4,5}; Object[] appendedArray = append(arr, arrToBeAdded); for (int i = 0; iWhen you run above program, you will get below output:
1 2 3 4 5As you can see, we are using object[] here. If you want to write a method specific to any data type, you can write that as well.
If you have frequent scenarios to add elements to array dynamically, I would recommend to use varargs instead of Array.That’s all about Java add to array.
The post Java add to array appeared first on Java2Blog.