1. Introduction

Searching for an element in an ArrayList is a fundamental operation in Java. It helps in determining whether a specific element is present in the list or not. In this blog post, we will look at how to search for an element in an ArrayList using the contains() method and the indexOf() method.

2. Program Steps

1. Initialize an ArrayList with some elements.

2. Use the contains() method to check if the ArrayList contains a specific element.

3. Use the indexOf() method to find the index of a specific element in the ArrayList.

3. Code Program

import java.util.ArrayList;
import java.util.List;

public class ArrayListSearchElement {

    public static void main(String[] args) {

        // Step 1: Initialize an ArrayList with some elements
        List<String> fruitList = new ArrayList<>();
        fruitList.add("Apple");
        fruitList.add("Banana");
        fruitList.add("Cherry");

        // Step 2: Use the contains() method to check if the ArrayList contains a specific element
        boolean containsApple = fruitList.contains("Apple");
        System.out.println("Does the list contain Apple? " + containsApple);

        // Step 3: Use the indexOf() method to find the index of a specific element in the ArrayList
        int indexOfBanana = fruitList.indexOf("Banana");
        System.out.println("Index of Banana in the list: " + indexOfBanana);
    }
}

Output:

Does the list contain Apple? true
Index of Banana in the list: 1

4. Step By Step Explanation

Step 1: We initialize an ArrayList named fruitList and add three elements to it – "Apple", "Banana", and "Cherry".

Step 2: The contains() method of the ArrayList class is used to check whether the ArrayList contains the element "Apple". This method returns a boolean value true if the element is found, and false otherwise. The result is then printed to the console.

Step 3: The indexOf() method is used to find the index of the element "Banana" in the ArrayList. If the element is present in the list, this method returns the index of the first occurrence of the element, otherwise, it returns -1. The index of "Banana" is found to be 1, and this is printed to the console.