1. Introduction

In Java, the LinkedList class provides the contains method that is used to check if a particular element is present in the list. This method returns a boolean value: true if the list contains the specified element, and false otherwise. In this post, we will demonstrate how to use the contains method in a Java LinkedList.

2. Program Steps

1. Create a LinkedList object and add elements to it.

2. Use the contains method to check if a particular element is present in the LinkedList.

3. Print the result to the console.

3. Code Program

import java.util.LinkedList;

public class LinkedListContainsExample {

    public static void main(String[] args) {

        // Step 1: Create a LinkedList object and add elements to it
        LinkedList<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        System.out.println("LinkedList: " + fruits);

        // Step 2: Use the contains method to check if a particular element is present in the LinkedList
        boolean containsBanana = fruits.contains("Banana");
        boolean containsGrapes = fruits.contains("Grapes");

        // Step 3: Print the result to the console
        System.out.println("Contains Banana? " + containsBanana);
        System.out.println("Contains Grapes? " + containsGrapes);
    }
}

Output:

LinkedList: [Apple, Banana, Cherry]
Contains Banana? true
Contains Grapes? false

4. Step By Step Explanation

Step 1: A LinkedList object named fruits is created and populated with the elements "Apple", "Banana", and "Cherry".

Step 2: The contains method is used to check whether the fruits list contains the elements "Banana" and "Grapes". The results are stored in boolean variables containsBanana and containsGrapes respectively.

Step 3: The boolean values are printed to the console, indicating whether the LinkedList contains the specified elements. The output shows that "Banana" is present in the list, returning true, while "Grapes" is not present, returning false.