Where is Java's Array indexOf?

Jamie picture Jamie · Feb 10, 2011 · Viewed 274.3k times · Source

I must be missing something very obvious, but I've searched all over and can't find this method.

Answer

Jeffrey Hantin picture Jeffrey Hantin · Feb 10, 2011

There are a couple of ways to accomplish this using the Arrays utility class.

If the array is not sorted and is not an array of primitives:

java.util.Arrays.asList(theArray).indexOf(o)

If the array is primitives and not sorted, one should use a solution offered by one of the other answers such as Kerem Baydoğan's, Andrew McKinlay's or Mishax's. The above code will compile even if theArray is primitive (possibly emitting a warning) but you'll get totally incorrect results nonetheless.

If the array is sorted, you can make use of a binary search for performance:

java.util.Arrays.binarySearch(theArray, o)