indexof
is a static method of the ArrayUtils
class that finds the index of a given element in the given array from the starting index.
A negative start index will be converted to zero.
-1
will be returned if the start index is larger than the length of the array.
-1
will be returned if the value cannot be found in the array.
4
is the result of the application of the indexOf
function because the element 5
is found at index 4
, which begins at index 2
.
-1
is the result of the application of the indexOf
function because the element 100
is not found in the array, which starts at the index 0
.
-1
is the result of the application of the indexOf
function because the start index is greater than the length of the array.
ArrayUtils
is defined in the To add Apache Commons Lang
package. 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 int indexOf(final int[] array, final int valueToFind, int startIndex)
final int[] array
: array of elements.final int valueToFind
: the element to be searched.final startIndex
: the start index from where the search begins.This function returns the index of the value at the given index, if it is found in the array. Otherwise, -1
is returned for the values not found in the array.
import org.apache.commons.lang3.ArrayUtils;public class Main {public static void main(String[] args) {int[] array = {1,2,3,4,5};System.out.println(ArrayUtils.indexOf(array, 5, 2));System.out.println(ArrayUtils.indexOf(array, 100, 0));System.out.println(ArrayUtils.indexOf(array, 3, 100));}}
4
-1
-1