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 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 ?