Java LinkedList contains() Method
contains()The method is, in Java,LinkedLista common method provided by the class, used to check whether the linked list contains the specified element. This method belongs tojava.util.LinkedListclass, and inherits fromjava.util.AbstractCollectionclass.
Method Syntax
public boolean contains(Object o)
Return Value
- If the linked list contains the specified element, it returns
true - If it does not contain the specified element, it returns
false
Method Details
How It Works
contains()The method traverses each element in the linked list and usesequals()method to compare each element with the target object. If a matching element is found, it immediately returnstrue; if the entire linked list is traversed without finding a matching element, it returnsfalse。
Time Complexity
SinceLinkedListis a doubly linked list,contains()The method needs to search sequentially from the head of the linked list, so its time complexity is O(n), where n is the number of elements in the linked list.
Usage Examples
Basic Usage
Example
public class LinkedListContainsExample {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> fruits = new LinkedList<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Check if element exists
System.out.println("Contains Apple? " + fruits.contains("Apple")); // Output: true
System.out.println("Contains Grape? " + fruits.contains("Grape")); // Output: false
}
}
Using Custom Objects
When using custom objects, you need to correctly overrideequals()method, otherwisecontains()method may not work as expected.
Example
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Override equals method
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && name.equals(person.name);
}
// Override hashCode method
@Override
public int hashCode() {
return 31 * name.hashCode() + age;
}
}
public class CustomObjectExample {
public static void main(String[] args) {
LinkedList<Person> people = new LinkedList<>();
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 30));
Person alice = new Person("Alice", 25);
System.out.println("Contains Alice? " + people.contains(alice)); // Output: true
}
}
Notes
1. Handling null Values
LinkedListAllows containingnullvalues, you can usecontains(null)to check whether the linked list containsnullvalue.
Example
list.add(null);
System.out.println(list.contains(null)); // Output: true
2. Performance Considerations
Sincecontains()method needs to traverse the linked list. For large linked lists, frequent calls to this method may affect performance. If you need to frequently check whether an element exists, you can consider usingHashSetand other data structures that are more suitable for searching.
3. Importance of the equals() Method
contains()The method relies on the element'sequals()method for object comparison. If the custom class does not correctly overrideequals()method,contains()method may not correctly identify equal objects.
Comparison with Other Methods
contains() vs indexOf()
contains(): returns boolean, only checks whether the element existsindexOf(): returns int, returns the index of the first occurrence of the element, or -1 if it does not exist
Example
list.add("A");
list.add("B");
list.add("A");
System.out.println(list.contains("A")); // Output: true
System.out.println(list.indexOf("A")); // Output: 0
contains() vs containsAll()
contains(): checks whether a single element existscontainsAll(): checks whether it contains all elements of the specified collection
Example
list.add("A");
list.add("B");
list.add("C");
System.out.println(list.contains("A")); // Output: true
List<String> checkList = Arrays.asList("A", "B");
System.out.println(list.containsAll(checkList)); // Output: true
Summary
LinkedListofcontains()The method is a simple but practical tool for checking whether a specific element exists in a linked list. Understanding how it works and using it correctly is very important for writing efficient Java programs. Remember the following points:
contains()The method usesequals()to compare elements- For custom objects, you must correctly override
equals()andhashCode()method - This method has a time complexity of O(n) and is not suitable for frequent use on large linked lists
- You can choose based on specific needs
indexOf()orcontainsAll()and other alternative methods
By usingcontains()method appropriately, you can effectively manage and manipulateLinkedListthe data in it.
Java LinkedList