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

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


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


Another option if you are using Guava Collections is Ints.indexOf

// Perfect storm:final int needle = 42;final int[] haystack = [1, 2, 3, 42];// Spoiler alert: index == 3final int index = Ints.indexOf(haystack, needle);

This is a great choice when space, time and code reuse are at a premium. It is also very terse.


A look at the API and it says you have to sort the array first

So:

Arrays.sort(array);Arrays.binarySearch(array, value);

If you don't want to sort the array:

public int find(double[] array, double value) {    for(int i=0; i<array.length; i++)          if(array[i] == value)             return i;}