To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.
The indexOf(Object) method of the java. util. ArrayList class returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Using this method, you can find the index of a given element.
To find the index of an element in a list, you use the index() function. It returns 3 as expected.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on. Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator.
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.
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.
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'));
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, 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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With