java array get index

java array get index

To get the index of an element in an array in Java, you can use the indexOf() method of the Arrays class.

Here is an example of how to get the index of an element in an array:

import java.util.Arrays;

public class ArrayGetIndexExample {

    public static void main(String[] args) {
        String[] colors = {"red", "green", "blue"};
        String element = "green";

        // Get the index of the element
        int index = Arrays.asList(colors).indexOf(element);

        if (index >= 0) {
            System.out.println("The element was found at index " + index);
        } else {
            System.out.println("The element was not found in the array");
        }
    }
}
Source:‮tual.www‬turi.com

In this example, the indexOf() method is used to get the index of the element string in the colors array. The indexOf() method returns the index of the element if it is found in the array, or -1 if the element is not found.

Alternatively, you can use a loop to manually iterate over the array and find the index of the element.

int index = -1;
for (int i = 0; i < colors.length; i++) {
    if (colors[i].equals(element)) {
        index = i;
        break;
    }
}
if (index >= 0) {
    System.out.println("The element was found at index " + index);
} else {
    System.out.println("The element was not found in the array");
}

Note that the indexOf() method uses the equals() method to compare the elements, so it is important to override the equals() method in your objects if you want to use the indexOf() method to search for element.

Created Time:2017-11-03 00:14:43  Author:lautturi