What is the LinkedList.contains method in Java?
Linked list
A Linked list is a collection of linear data elements. Each element (or node) contains data and reference parts.
The data part has the value and the reference part has the address to the next element.
The elements are not indexed. so random access is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedListis the Doubly-linked list implementation of the List and Deque interfaces.
The LinkedList is class present in the java.util package.
What is contains method of LinkedList class?
The contains method is used to check if an element is present in the LinkedList.
Syntax
public boolean contains(Object o)
Parameter
This method takes the element to be checked for presence, as a parameter.
Return value
This method returns true if the passed element is present in the list. Otherwise, it returns false.
Code
The code below demonstrates how to use the contains method.
import java.util.LinkedList;class LinkedListGetExample {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("3");System.out.println("The list is " + list);System.out.println("Check if 1 present in the list : " + list.contains("1"));System.out.println("Check if 4 present in the list : " + list.contains("4"));}}
Explanation
In the code above:
- In line number 1: We import the
LinkedListclass.
import java.util.LinkedList;
- In line number 4: We create a
LinkedListobjects with the namelist.
LinkedList<String> list = new LinkedList<>();
- From line number 5 to 7: We use the
addmethod of thelistobject to add three elements("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("3");
- On line number 10: We use the
containsmethod of thelistobject to check if the element"1"is present in the list. We gettrueas result.
list.contains("1"); // true
- On line number 11: We use the
containsmethod to check if the element"4"is present in the list. We getfalseas result, because"4"is not present in the list.
list.contains("4"); // false