Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement