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

Jeomark picture Jeomark · May 30, 2011 · Viewed 499k times · Source

How can I find an index of a certain value in a Java array of type int?

I tried using Arrays.binarySearch on my unsorted array, it only sometimes gives the correct answer.

Answer

Pablo Fernandez picture Pablo Fernandez · May 30, 2011
Integer[] array = {1,2,3,4,5,6};

Arrays.asList(array).indexOf(4);

Note that this solution is threadsafe because it creates a new object of type List.

Also you don't want to invoke this in a loop or something like that since you would be creating a new object every time