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

前端 未结 19 1363
南方客
南方客 2020-11-27 02:56

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

19条回答
  •  借酒劲吻你
    2020-11-27 03:06

    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 ?

提交回复
热议问题