Java Basic Examples

Java array indexOf example

Java array indexOf example shows how to find index of element in array. 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 index of element in array?

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

Output

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

Please note that this code does not work for arrays of primitive types like int, float, char, double etc. If that is the case, we need to write our own indexOf method as given below.

Output

If the array is sorted, you can also use 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) Does not always return -1 if element is not found, but a negative value according to insertion point as you can see from the output.
3) Works for both primitives as well as Objects. If the array is of custom type, the custom type must implement Comparable or you can use overloaded binarySearch method which accepts Comparator.

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

Output

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *