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:
JavaScript
x
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:
JavaScript
System.out.println(new String(list).indexOf("e"));
But in other cases of primitive data types, you’ll have to iterate over it.