What is ArrayUtils.swap in Java?

swap is a static method of the ArrayUtils class that swaps the positions of two elements in an array.

Characteristics

  • The swap operation is in-place in nature, i.e., the modification is done to the original array.

  • Negative indices are promoted to zero.

  • The swap operation is not applied for the following conditions:

    • The input array is null.

    • The input indices lead to overflow.

    • The input array is empty.

Syntax


public static void swap(final int[] array, final int offset1, final int offset2)

Parameters

  • final int[] array: holds the array with the elements that need to be swapped.

  • final int offset1: holds the index of the first element to swap.

  • final int offset2: holds the index of the second element to swap.

Return value

The method doesn’t return anything, as the modification is applied to the original array passed as an argument.

Add the Apache Commons Lang package

ArrayUtils is defined in the Apache Commons Lang package. To add Apache Commons Lang to the Maven Project, add 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.


How to import ArrayUtils

You can import the ArrayUtils class as follows.


import org.apache.commons.lang3.ArrayUtils;

Code

Example 1

  • array = [1,2,3,4,5]

Let’s say we want to swap the elements at offsets (position) 1 & 4.

Application of the swap function will result in the following array: [5, 2, 3, 4, 1].

The element at position 1, i.e., 2, is swapped with the element at position 4, i.e., 5.

Example 2

  • array = [1,2,3,4,5]

Let’s say we want to swap the elements at offsets (position) -4 & 4.

Application of the swap function will result in the following array: [5, 2, 3, 4, 1].

The first negative index will be changed to 0 (zero). Hence, the element at position 0, i.e., 1, is swapped at position 4, i.e., 5.

import org.apache.commons.lang3.ArrayUtils;
public class Main {
public static void main( String args[] ) {
int[] array = {1,2,3,4,5};
System.out.print("Original Array - ");
for(int i: array){
System.out.print(i + " ");
}
ArrayUtils.swap(array, 1,4);
System.out.print("\nModified Array after swapping - ");
for(int i: array){
System.out.print(i + " ");
}
}
}

Output


Original Array - 1 2 3 4 5 
Modified Array after swapping - 1 5 3 4 2

Free Resources