Java ArrayList IndexOf() Method
What is an ArrayList ?
Arraylist is a part of collection framework in java. It contains several inbuilt method like IndexOf() method which can be found in the java.util.ArrayList Package. It implements the List interface of the collections framework.
Here, in the page we will discuss about the ArrayList’s indexOf() Method in java.
ArrayList indexOf() Function:
Syntax :
arraylist.indexOf(Object obj)
Return Type :
Example code :
//This is the Example code for ArraryList indexOf() Method import java.util.*; public class Main{ public static void main(String[] args) { ArrayList list = new ArrayList<>(); //Adding elements to the list list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); list.add("F"); //Printing the index of the elements System.out.println(list.indexOf("A")); System.out.println(list.indexOf("B")); System.out.println(list.indexOf("C")); System.out.println(list.indexOf("D")); System.out.println(list.indexOf("E")); System.out.println(list.indexOf("F")); System.out.println(list.indexOf("G")); } }
Output :
0 1 2 3 4 5 -1 //We get -1 here because G is not present in the list
Explanation :
This code example demonstrates the use of the indexOf() method in Java’s ArrayList. The code creates an ArrayList of Strings and adds elements (“A”, “B”, “C”, “D”, “E”, and “F”) to the list. The indexOf() method is then used to find the index of each element in the list and print it. If the element is not found in the list, the indexOf() method returns -1, which is the case for the element “G”.
import java.util.*; public class Main { public static void main(String[] args) { ArrayList numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5); int index = numbers.indexOf(3); System.out.println("Index of 3: " + index); index = numbers.indexOf(6); System.out.println("Index of 6: " + index); } }
Output :
Index of 3: 2 Index of 6: -1
Explanation :
In this example, an ArrayList of Integers is created and populated with 5 elements (1, 2, 3, 4, and 5). The indexOf() method is then used to find the index of the number 3 in the list and print it. If the number is not found in the list, the indexOf() method returns -1, which is the case for the number 6.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment