anon
anon

Reputation:

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

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?

Upvotes: 78

Views: 463960

Answers (15)

user14825208
user14825208

Reputation: 1

int i = 0;
int count = 1;
        while ('e'!= list[i] ) {
            i++;
            count++;
        }

        System.out.println(count);

Upvotes: -2

Roshini
Roshini

Reputation: 85

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);
 }}

Upvotes: -1

Salvador Vigo
Salvador Vigo

Reputation: 457

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;
}

Upvotes: 1

Tung Tran
Tung Tran

Reputation: 2955

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;
    }
}

Upvotes: 6

Tunaki
Tunaki

Reputation: 137084

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.

Upvotes: 25

Kehe CAI
Kehe CAI

Reputation: 1221

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"
}

Upvotes: 3

Max77
Max77

Reputation: 1566

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.

Upvotes: 48

Manmohan Soni
Manmohan Soni

Reputation: 6621

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;
    }

Upvotes: 0

OscarRyz
OscarRyz

Reputation: 199225

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 )

Upvotes: 2

Bill K
Bill K

Reputation: 62769

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

Upvotes: 1

Powerlord
Powerlord

Reputation: 88796

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') );
    } 
}

Upvotes: 1

Matt Solnit
Matt Solnit

Reputation: 33544

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;
  }
}

Upvotes: 8

Joey
Joey

Reputation: 354526

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'));

Upvotes: 20

Peter
Peter

Reputation: 8575

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

Upvotes: 5

Bart Kiers
Bart Kiers

Reputation: 170158

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.

Upvotes: 68

Related Questions