Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
arrayutils
value
index
communitycreator

What is ArrayUtils.get in Java?

abhilash

get is a static method of the ArrayUtils class that returns the value at a given index. The method returns the default value passed if the index is out of bounds.

The method returns the default value passed as a parameter if the input array is null.

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.

You can import the ArrayUtils class as follows.

import org.apache.commons.lang3.ArrayUtils;

Syntax

public static <T> T get(final T[] array, final int index, final T defaultValue)

Parameters

  • final T[] array : Array of elements.
  • final int index : Index value.
  • final T defaultValue : The return value if the index is out of bounds or the array is null.

Type parameters

  • <T> : The type of array elements.

Returns

This returns the array element found at the index, if the index is within the bounds. Otherwise, the default value passed.

Code examples

import org.apache.commons.lang3.ArrayUtils;

public class Main {

    public static void main(String[] args) {
        Integer[] array = {1,2,3,4,5};
        //Example 1
        System.out.println(ArrayUtils.get(array, 3, -100));
        //Example 2
        System.out.println(ArrayUtils.get(array, 10, -100));
        //Example 3
        System.out.println(ArrayUtils.get(null, 10, -100));
    }
}

Output

4
-100
-100

Example 1

  • Array = [1,2,3,4,5]
  • Index = 3
  • Default value: -100

4 is a result of the application of the get function because the index is within the bounds.

Example 2

  • Array = [1,2,3,4,5]
  • Index = 10
  • Default value: -100

-100 is the result of the application of the get function because the index is out of the bounds.

Example 3

  • Array = null
  • Index = 3
  • Default value: -100

-100is the result of the application of the get function because the array is null.

RELATED TAGS

java
arrayutils
value
index
communitycreator
RELATED COURSES

View all Courses

Keep Exploring