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 som
You could convert it to a list, then use the indexOf method:
Array.asList(array).indexOf(1);
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#asList(T...) http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html#indexOf(java.lang.Object)
You can either walk through the array until you find the index you're looking for, or use a List
instead. Note that you can transform the array into a list with asList().
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 == 3
final 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.
You need to sort values before using binary search. Otherwise, the manual way is to try all ints in your tab.
public int getIndexOf( int toSearch, int[] tab )
{
for( int i=0; i< tab.length ; i ++ )
if( tab[ i ] == toSearch)
return i;
return -1;
}//met
An alternative method could be to map all index for each value in a map.
tab[ index ] = value;
if( map.get( value) == null || map.get( value) > index )
map.put( value, index );
and then map.get(value) to get the index.
Regards, Stéphane
@pst, thanks for your comments. Can you post an other alternative method ?
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;
}
Simple:
public int getArrayIndex(int[] arr,int value) {
for(int i=0;i<arr.length;i++)
if(arr[i]==value) return i;
return -1;
}