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
LinkedList
is the Doubly-linked list implementation of the List and Deque interfaces.
The LinkedList
is class present in the java.util
package.
contains
method of LinkedList
class?The contains
method is used to check if an element is present in the LinkedList
.
public boolean contains(Object o)
This method takes the element to be checked for presence, as a parameter.
This method returns true
if the passed element is present in the list. Otherwise, it returns false
.
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"));}}
In the code above:
LinkedList
class.import java.util.LinkedList;
LinkedList
objects with the name list
.LinkedList<String> list = new LinkedList<>();
add
method of the list
object to add three elements("1","2","3"
) to the list.list.add("1");
list.add("2");
list.add("3");
contains
method of the list
object to check if the element "1"
is present in the list. We get true
as result.list.contains("1"); // true
contains
method to check if the element "4"
is present in the list. We get false
as result, because "4"
is not present in the list.list.contains("4"); // false