Skip to content

Find index of an element in LinkedList in Java example

This example shows how to find the index of an element in the LinkedList in Java. This example also shows how to find the index of the first and last occurrence of an element using indexOf and lastIndexOf methods.

How to find the index of an element in the LinkedList in Java?

Use the indexOf method of the LinkedList class to find the index of the first occurrence of an element in the list.

The indexOf method returns the index of the first occurrence of the specified element object in the list. If the specified element is not found in the list. it returns -1.

Similarly, use the lastIndexOf method of the LinkedList class to find the last occurrence of the specified element in the list.

This method also returns -1 if the element is not found in the list, otherwise, it returns the index of the last occurrence of the specified element in the list.

Output

How to find the index of a custom class object in the LinkedList?

The indexOf and lastIndexOf methods rely on the equals method to do the equality comparison. In the above example, we have used the Integer class as elements of the LinkedList which has implemented the equals method.

In the case of the custom class objects, these methods will not work properly if the custom class has not implemented the equals method. It is because if the custom class has not implemented the equals method, then the equals method of the Object class will be used by these methods which only compares the object references, not the actual objects.

The below example shows how to define the equals and hashCode methods for the custom class so that the indexOf and lastIndexOf methods can be used to find the objects.

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

Leave a Reply

Your email address will not be published.