To get the index of an element in an ArrayList
in Java, you can use the indexOf()
method of the ArrayList
class. This method takes an element as an argument and returns the index of the first occurrence of the element in the list, or -1
if the element is not present in the list.
Here's an example of how you can get the index of an element in an ArrayList
in Java:
import java.util.ArrayList; // ... ArrayList<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); names.add("David"); int index = names.indexOf("Charlie");
In this example, the names
list is an ArrayList
object containing four strings. The index
variable holds the index of the element "Charlie" in the list.
You can also use the lastIndexOf()
method to get the index of the last occurrence of an element in the list.