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

前端 未结 19 1252
南方客
南方客 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:01

    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)

    0 讨论(0)
  • 2020-11-27 03:01

    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().

    0 讨论(0)
  • 2020-11-27 03:03

    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.

    0 讨论(0)
  • 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 ?

    0 讨论(0)
  • 2020-11-27 03:08

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 03:09

    Simple:

    public int getArrayIndex(int[] arr,int value) {
        for(int i=0;i<arr.length;i++)
            if(arr[i]==value) return i;
        return -1;
    }
    
    0 讨论(0)
提交回复
热议问题