1. Introduction
Searching for an element in a LinkedList is a common operation in Java. The contains() method of the LinkedList class can be used for this purpose. It returns true if the list contains the specified element, otherwise false.
2. Program Steps
1. Create a LinkedList and add some elements to it.
2. Use the contains() method to check whether the list contains a specified element.
3. Print the result.
3. Code Program
import java.util.LinkedList;
public class LinkedListSearchExample {
public static void main(String[] args) {
// Step 1: Create a LinkedList and add some elements
LinkedList<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Step 2: Use the contains() method to check whether the list contains "Banana"
boolean containsBanana = fruits.contains("Banana");
// Step 3: Print the result
System.out.println("Does the LinkedList contain Banana? " + containsBanana);
}
}
Output:
Does the LinkedList contain Banana? true
4. Step By Step Explanation
Step 1: A LinkedList named fruits is created, and three elements ("Apple", "Banana", "Cherry") are added to it.
Step 2: The contains() method is called on the fruits LinkedList to check whether it contains the element "Banana".
Step 3: The result (true) is printed to the console, indicating that "Banana" is indeed present in the fruits LinkedList.