Check If Element Exists in LinkedList in Java example

This example shows how to check if the element exists in the LinkedList in Java. This example also shows how to check if LinkedList contains an object of a custom class.

How to check if the element exists in the LinkedList in Java?

The contains method of the LinkedList class can be used to check if the element exists in the linked list.

The contains method returns true if the specified object exists in the linked list, false otherwise. In other words, if the linked list contains the element, it returns true.

Output

How to check if the LinkedList contains an object of a custom class?

The contains method of the LinkedList class returns true if and only if the list contains an element that is equal to the specified element. This equality check is done using the equals method. The above example worked as expected because the Java String class has implemented the equals method.

If the linked list you are using has objects of a custom class then the custom class must implement the equals and hashCode methods for the contains method to work properly. Let’s see an example of that.

Output

As you can see from the output, even if the linked list contains the specified object, the contains method returned false.

Since our Employee class has not implemented the equals method, the equals method of the Object class was used to compare the objects. The equals method of the Object class compares the object references which are different in our case and that is why the contains method returned false.

Let’s implement the equals and hashCode methods in our Employee class and try again.

Output

This example is a part of the LinkedList in Java tutorial.

Please let me know your views in the comments section below.

References:
Java 8 LinkedList

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *