English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
O método indexOf() do Java ArrayList retorna a posição do elemento especificado no arraylist.
A sintaxe do método indexOf() é:
arraylist.indexOf(Object obj)
obj - O elemento a retornar sua posição
Se o mesmo elemento obj existir em várias posições, retorna a posição do primeiro aparecimento do elemento no arraylist.
Retornar a posição do elemento especificado do arraylist
Note:Se o elemento especificado não existir na lista, o método indexOf() retorna -1。
import java.util.ArrayList; class Main { public static void main(String[] args) { //Criar ArrayList ArrayList<Integer> numbers = new ArrayList<>(); // Inserir elemento no arraylist numbers.add(22); numbers.add(13); numbers.add(35); System.out.println("ArrayList de Número: " + numbers); //Procurar elemento13A posição int posição1 = numbers.indexOf(13); System.out.println("13O valor do índice: " + posição1); //Procurar elemento5A posição 0 int posição2 = numbers.indexOf(50); System.out.println("5O valor do índice 0: " + posição2); } }
Output Result
ArrayList de Número: [22, 13, 35] 13O valor do índice: 1 5O valor do índice 0: -1
No exemplo acima, criamos uma lista de array chamada numbers. Note essas expressões,
// Reverter 1 numbers.indexOf(13) // Retorna -1 numbers.indexOf(5(0)
Aqui, o método indexOf() retorna com sucesso a posição do elemento13a posição. No entanto, o elemento50O elemento não existe no arraylist. Portanto, o método retorna-1。
import java.util.ArrayList; class Main { public static void main(String[] args) { //Criar ArrayList ArrayList<String> languages = new ArrayList<>(); //Inserir elemento no arraylist languages.add("JavaScript"); languages.add("Python"); languages.add("Java"); languages.add("C");++"); languages.add("Java"); System.out.println("Linguagem de programação: " + languages); //Get the position of Java int position = languages.indexOf("Java"); System.out.println("First occurrence of Java: ", + position); } }
Output Result
Programming Language: [JavaScript, Python, Java, C++, Java] First occurrence of Java: 2
In the above example, we created an array list named languages. Here, we use the indexOf() method to get the position of the element Java.
But, Java exists in two different positions in the list. In this case, the method returns the first occurrence of Java (i.e.,2position).
And, if we want to get the last occurrence of Java, we can use the lastIndexOf() method.
NoteWe can also useJava ArrayList get()Method to get the element at the specified position.