76

I am looking to find the index of a given element, knowing its contents, in Java.

I tried the following example, which does not work:

class masi { 
    public static void main( String[] args ) { 
        char[] list = {'m', 'e', 'y'};

        // should print 1
        System.out.println(list[] == "e");                    
    } 
}

Can anyone please explain what is wrong with this and what I need to do to fix it?

15 Answers15

67

In this case, you could create e new String from your array of chars and then do an indeoxOf("e") on that String:

System.out.println(new String(list).indexOf("e")); 

But in other cases of primitive data types, you'll have to iterate over it.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
41

Alternatively, you can use Commons Lang ArrayUtils class:

int[] arr = new int{3, 5, 1, 4, 2};
int indexOfTwo = ArrayUtils.indexOf(arr, 2);

There are overloaded variants of indexOf() method for different array types.

Max77
  • 1,466
  • 13
  • 19
  • 2
    This is the best way to do it. If you don't have apache in your project, add it. Another way is to use java.util.Arrays.binarySearch but it needs a sorted array, so not always useful. – Bogdan Oct 23 '14 at 11:37
  • 1
    Can you also write here the full implementation to add to the project? – Gili Ariel Aug 15 '20 at 10:32
23

For primitive arrays

Starting with Java 8, the general purpose solution for a primitive array arr, and a value to search val, is:

public static int indexOf(char[] arr, char val) {
    return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}

This code creates a stream over the indexes of the array with IntStream.range, filters the indexes to keep only those where the array's element at that index is equal to the value searched and finally keeps the first one matched with findFirst. findFirst returns an OptionalInt, as it is possible that no matching indexes were found. So we invoke orElse(-1) to either return the value found or -1 if none were found.

Overloads can be added for int[], long[], etc. The body of the method will remain the same.

For Object arrays

For object arrays, like String[], we could use the same idea and have the filtering step using the equals method, or Objects.equals to consider two null elements equal, instead of ==.

But we can do it in a simpler manner with:

public static <T> int indexOf(T[] arr, T val) {
    return Arrays.asList(arr).indexOf(val);
}

This creates a list wrapper for the input array using Arrays.asList and searches the index of the element with indexOf.

This solution does not work for primitive arrays, as shown here: a primitive array like int[] is not an Object[] but an Object; as such, invoking asList on it creates a list of a single element, which is the given array, not a list of the elements of the array.

Community
  • 1
  • 1
Tunaki
  • 132,869
  • 46
  • 340
  • 423
21

That's not even valid syntax. And you're trying to compare to a string. For arrays you would have to walk the array yourself:

public class T {
  public static void main( String args[] ) {
    char[] list = {'m', 'e', 'y'};

    int index = -1;

    for (int i = 0; (i < list.length) && (index == -1); i++) {
        if (list[i] == 'e') {
            index = i;
        }
    }

    System.out.println(index);
  }
}

If you are using a collection, such as ArrayList<Character> you can also use the indexOf() method:

ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');

System.out.println(list.indexOf('e'));

There is also the Arrays class which shortens above code:

List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));
Joey
  • 344,408
  • 85
  • 689
  • 683
  • I very much doubt there is a `list` type you can build an array from. If there is, naming conventions are gravely violated. – Joey Oct 05 '09 at 20:36
  • `List` defineas a `toArray` method – skaffman Oct 05 '09 at 20:52
  • That was a reply to aperkins who apparently gave me a downvote for my statement that `list[] == "e"` was invalid syntax. For the `[]` to work, `list` has to be a type, not a variable. That's what I meant with "`list` type to build an array from". Sorry for the misunderstanding. – Joey Oct 05 '09 at 21:24
8

I believe the only sanest way to do this is to manually iterate through the array.

for (int i = 0; i < list.length; i++) {
  if (list[i] == 'e') {
    System.out.println(i);
    break;
  }
}
Matt Solnit
  • 32,152
  • 8
  • 53
  • 57
6

Simplest solution:

Convert array to list and you can get position of an element.

List<String> abcd  = Arrays.asList(yourArray);
int i = abcd.indexOf("abcd");

Other solution, you can iterator array:

int position = 0;
for (String obj : yourArray) {
    if (obj.equals("abcd") {
    return position;
    }
    position += 1;
} 

//OR
for (int i = 0; i < yourArray.length; i++) {
    if (obj.equals("abcd") {
       return i;
    }
}
Tung Tran
  • 2,885
  • 2
  • 17
  • 24
5

The problem with your code is that when you do

 list[] == "e"

you're asking if the array object (not the contents) is equal to the string "e", which is clearly not the case.

You'll want to iterate over the contents in order to do the check you want:

 for(String element : list) {
      if (element.equals("e")) {
           // do something here
      }
 }
Peter
  • 8,545
  • 1
  • 27
  • 24
3

This way should work, change "char" to "Character":

public static void main(String[] args){
  Character[] list = {'m', 'e', 'y'};
  System.out.println(Arrays.asList(list).indexOf('e')); // print "1"
}
Kehe CAI
  • 1,161
  • 12
  • 18
2

Now it does print 1

class Masi {
    public static void main( String [] args ) {
         char [] list = { 'm', 'e', 'y' };

         // Prints 1
         System.out.println( indexOf( 'e', list ) );
    }

    private static int indexOf( char c , char [] arr ) {
        for( int i = 0 ; i < arr.length ; i++ ) {
            if( arr[i] == c ) { 
                return i;
            }
         }
         return -1;
     }
 }

Bear in mind that

"e"

is an string object literal ( which represents an string object that is )

While

'e'

Is a character literal ( which represents a character primitive datatype )

Even when

list[]

Would be valid Java ( which is not ) comparing the a character element with a string element would return false anyway.

Just use that indexOf string function and you could find any character within any alphabet ( or array of characters )

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
1

Very Heavily Edited. I think either you want this:

class CharStorage {
    /** set offset to 1 if you want b=1, o=2, y=3 instead of b=0... */
    private final int offset=0;
    private int array[]=new int[26];

    /** Call this with up to 26 characters to initialize the array.  For 
      * instance, if you pass "boy" it will init to b=0,o=1,y=2.
      */
    void init(String s) {
        for(int i=0;i<s.length;i++)
            store(s.charAt(i)-'a' + offset,i); 
    }

    void store(char ch, int value) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        array[ch-'a']=value;
    }

    int get(char ch) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        return array[ch-'a'];
    }
}

(Note that you may have to adjust the init method if you want to use 1-26 instead of 0-25)

or you want this:

int getLetterPossitionInAlphabet(char c) {
    return c - 'a' + 1
}

The second is if you always want a=1, z=26. The first will let you put in a string like "qwerty" and assign q=0, w=1, e=2, r=3...

Bill K
  • 62,186
  • 18
  • 105
  • 157
1

If the initial order of elements isn't really important, you could just sort the array, then binarySearch it:

import java.util.Arrays;

class masi { 
    public static void main( String[] args ) { 
        char[] list = {'m', 'e', 'y'};
        Arrays.sort(list);

        // should print 0, as e is now sorted to the beginning
        // returns negative number if the result isn't found
        System.out.println( Arrays.binarySearch(list, 'e') );
    } 
}
Powerlord
  • 87,612
  • 17
  • 125
  • 175
1

here is another example and how indexOf is working.

public int indexOf(Object target) {
    for (int i = 0; i < array.length; i++) {
        if (equals(target, array[i])) {
            return i;
        }
    }
    return -1;
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
Salvador Vigo
  • 397
  • 4
  • 16
0

I am providing the proper method to do this one

/**
     * Method to get the index of the given item from the list
     * @param stringArray
     * @param name
     * @return index of the item if item exists else return -1
     */
    public static int getIndexOfItemInArray(String[] stringArray, String name) {
        if (stringArray != null && stringArray.length > 0) {
            ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
            int index = list.indexOf(name);
            list.clear();
            return index;
        }
        return -1;
    }
Manmohan Soni
  • 6,472
  • 2
  • 23
  • 29
  • Don't convert to an `ArrayList`, and don't call `list.clear()`. Those are iterating the array 2 extra times. – 4castle Oct 02 '16 at 16:31
-1

This way you can use upto 'N' letters.

char[] a={ 'a', 'b', 'c', 'd', 'e' };
int indexOf=0;
for(int i=0;i<a.length;i++){
  if(a[i] != 'b'){
    indexOf++;
    }else{
    System.out.println("index of given: "+indexOf);
 }}
Roshini
  • 85
  • 1
  • 8
-2
int i = 0;
int count = 1;
        while ('e'!= list[i] ) {
            i++;
            count++;
        }

        System.out.println(count);