Table of Contents
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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; i < appendedArray.length; i++) { System.out.print(" "+appendedArray[i]); } } } |
When you run above program, you will get below output.
By 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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; i < appendedArray.length; i++) { System.out.print(" "+appendedArray[i]); } } static Object[] append(Object[] arr, Object...elements) { final int N = arr.length; Object[] temp = Arrays.copyOf(arr, N + elements.length); for(int i=0; i < elements.length; i++) temp[arr.length+i] = elements[i]; return temp; } } |
When you run above program, you will get below output:
As 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.