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;
public static <T> T get(final T[] array, final int index, final T defaultValue)
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.<T>
: The type of array elements.This returns the array element found at the index, if the index is within the bounds. Otherwise, the default value passed.
import org.apache.commons.lang3.ArrayUtils;public class Main {public static void main(String[] args) {Integer[] array = {1,2,3,4,5};//Example 1System.out.println(ArrayUtils.get(array, 3, -100));//Example 2System.out.println(ArrayUtils.get(array, 10, -100));//Example 3System.out.println(ArrayUtils.get(null, 10, -100));}}
4
-100
-100
-100
4
is a result of the application of the get
function because the index is within the bounds.
-100
-100
is the result of the application of the get
function because the index is out of the bounds.
-100
-100
is the result of the application of the get
function because the array is null
.