Introduction
The contains()
method in Java's LinkedList
class is a handy tool to check if a specific element exists within the list. Think of it like searching for something in a drawer – you want to quickly confirm if what you’re looking for is already there.
Syntax
public boolean contains(Object o)
Parameters
Parameter | Description |
---|---|
o |
The object to be checked for equality. It can be any type of object. |
Return Value
The contains()
method returns a boolean value:
true
: If the list contains the specified element.false
: If the list does not contain the specified element.
Examples
Example 1: Checking for a String Element
This example demonstrates how to use contains()
to see if a specific string is present in a LinkedList of strings.
import java.util.LinkedList;
public class ContainsExample {
public static void main(String[] args) {
LinkedList<String> names = new LinkedList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
String searchName = "Bob";
boolean containsBob = names.contains(searchName);
System.out.println("Does the list contain '" + searchName + "'? " + containsBob);
}
}
Does the list contain 'Bob'? true
Explanation: We create a LinkedList of strings. Then, we use contains()
to check if it contains the string "Bob". Since "Bob" is present in the list, the method returns true
.
Example 2: Checking for an Integer Element
This example shows how to use contains()
with a LinkedList of integers.
import java.util.LinkedList;
public class ContainsIntegerExample {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
int searchNumber = 40;
boolean containsForty = numbers.contains(searchNumber);
System.out.println("Does the list contain " + searchNumber + '? ' + containsForty);
}
}
Does the list contain 40? false
Explanation: We create a LinkedList of integers. We then use contains()
to check if it contains the integer 40. Since 40 is not in the list, the method returns false
.
Example 3: Checking for an Object with Null
This example demonstrates how the LinkedList handles null values when using the contains() method
import java.util.LinkedList;
public class ContainsNullExample {
public static void main(String[] args) {
LinkedList<String> strings = new LinkedList<>();
strings.add("Hello");
strings.add(null);
strings.add("World");
boolean containsNull = strings.contains(null);
System.out.println("Does the list contain null? " + containsNull);
}
}
Does the list contain null? true
Explanation: A LinkedList can contain null values, and contains(null)
will return true
if a null value is present in the list.