add
is a static method of the ArrayUtils
class that copies the elements of the given array to a new array and appends the given element to the end of the new array.
If the input array is null
, add
returns a new one-element array with the given element. The component type of the new array is the same as that of the given element.
Application of the add
function will result in the following array: [1,2,3,4,5,10]
.
Application of the add
function will result in the following array: [10]
.
ArrayUtils
is defined in theApache Commons Lang
package. To addApache Commons Lang
to the Maven Project, add the following dependency to thepom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the
ArrayUtils
class as follows.
import org.apache.commons.lang3.ArrayUtils;
public static int[] add(final int[] array, final int element)
final int[] array
: array of elements.final int element
: the element to be added at the end of the array.add
returns a new array that contains the existing elements with the new element appended at the end of the new array.
import org.apache.commons.lang3.ArrayUtils;public class Main {public static void main(String[] args) {int[] array = new int[]{1,2,3,4,5,2,3,2,2,4};System.out.print("Original Array - ");for(int i: array){System.out.print(i + " ");}int elementToAdd = 100;int[] result = ArrayUtils.add(array, elementToAdd);System.out.print("\nModified Array after adding element - ");for(int i: result){System.out.print(i + " ");}}}
Original Array - 1 2 3 4 5 2 3 2 2 4
Modified Array after adding element - 1 2 3 4 5 2 3 2 2 4 100