Skip to content

Java array indexOf example

Java array indexOf example shows how to find index of element in array. The example also shows how to find index of element in primitive as well as object arrays and custom Java array indexOf method implementation.

How to find the index of an element in an array?

Java arrays are objects, however, they do not provide an indexOf method. In order to search the element and get its index, we need to implement our own indexOf method. Here is the sample code for that.

Output

We first converted the array to List using the asList method of the Arrays class. This method returns the List wrapper of the existing array. Since the List class has an indexOf method, we can use it to find an element index.

Please note that this code does not work for arrays of primitive types like int, float, char, double, etc. For primitive types like these, we need to write our own indexOf method per type. The below-given code example shows the custom indexOf method for the int type.

Output

Additionally, If the array is sorted, you can also use the binarySearch method of Arrays class as given below.

Output

It is important to note that the above method,
1) Changes the original array by sorting it
2) It does not always return -1 if the element is not found, but a negative value according to the insertion point as you can see from the output.
3) It works for both primitives as well as Objects. If the array is of a custom type, the custom type must implement the Comparable or you can use an overloaded binarySearch method which accepts Comparator argument.

And finally, if you are using the Apache Commons, you can use the indexOf method of ArrayUtils class as given below.

Output

This example is a part of the Java Array tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.