Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
array
addall
communitycreator

What is ArrayUtils.addAll in Java?

abhilash

addAll is a static method of the ArrayUtils class that returns a new array containing all the elements of the given arrays.

The new array is a combination of the elements of the first array and the elements of the second array.

Example 1

  • array1 = [1,2,3,4,5]
  • array2 = [4,3,1]

The array [1,2,3,4,5,4,3,1] is a result of applying the addAll function, becuase the elements of the first array are followed by the elements of the second array.

Example 2

  • array1 = [1,2,3,4,5]
  • array2 = null

The array [1,2,3,4,5] is a result of applying the addAll function, because the second array is null.

Add apache commons-lang package

ArrayUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.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.


Import ArrayUtils

You can import the ArrayUtils class as follows:


import org.apache.commons.lang3.ArrayUtils;

Syntax

public static int[] addAll(final int[] array1, final int... array2)

Parameters

  • final int[] array1 is the first array.

  • final int... array2 is the second array.

Returns

A new array containing the elements of the first array, followed by the elements of the second array is returned.

Code

import org.apache.commons.lang3.ArrayUtils;

public class Main {

    private static void printArray(int[] array){
        System.out.print("[ ");
        for(int i:array) System.out.print( i + " ");
        System.out.println("]");
    }

    public static void main(String[] args) {
        int[] array1 = {1,2,3,4,5};
        System.out.print("Array1 is - ");
        printArray(array1);

        int[] array2 = {4, 3, 1};
        System.out.print("Array2 is - ");
        printArray(array2);
        int[] combinedArray = ArrayUtils.addAll(array1, array2);
        System.out.print("Combined Array is - ");
        printArray(combinedArray);
    }
}

Output


Array1 is - [ 1 2 3 4 5 ]
Array2 is - [ 4 3 1 ]
Combined Array is - [ 1 2 3 4 5 4 3 1 ]

RELATED TAGS

java
array
addall
communitycreator
RELATED COURSES

View all Courses

Keep Exploring