isArrayIndexValid
is a static method of the ArrayUtils
class that states whether a given index is within the bounds of the array, i.e., the index should be greater than or equal to zero and less than the length of the array.
0 <= index < array_length
Arrays in Java follow zero-based indexing.
[1,2,3,4,5]
2
Applying the isArrayIndexValid
function will result in true
, as the index is within the bounds.
[1,2,3,4,5]
10
Applying the isArrayIndexValid
function will result in false
, as the index is out of bounds.
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.
You can import the ArrayUtils
class as follows:
import org.apache.commons.lang3.ArrayUtils;
public static <T> boolean isArrayIndexValid(final T[] array, final int index)
final T[] array
: An array of elements.final int index
: Index to check.<T>
: The data type of the array.This method returns true
if the index can be safely accessed in the given array, and returns false
otherwise.
import org.apache.commons.lang3.ArrayUtils; public class Main { public static void main(String[] args) { Integer[] array = {1,2,3,4,5,2,3,2,2,4}; boolean check = ArrayUtils.isArrayIndexValid(array, 3); System.out.println("Index 3 is accessible in the array - " + check); check = ArrayUtils.isArrayIndexValid(array, 100); System.out.println("Index 100 is accessible in the array - " + check); } }
Index 3 is accessible in the array - true
Index 100 is accessible in the array - false
RELATED TAGS
CONTRIBUTOR
View all Courses