Skip to content

Find element in ArrayList using indexOf lastIndexOf methods example

Find an element in ArrayList using indexOf lastIndexOf methods example shows how to find element in ArrayList using indexOf and lastIndexOf methods in Java. It also shows how to find an object of a custom class in ArrayList by implementing equals and hashCode methods.

How to find an element in ArrayList using the indexOf lastIndexOf methods in Java?

The ArrayList indexOf method returns the index of an element in the ArrayList object.

This method returns the index of the first occurrence of the specified object in the ArrayList. If the specified object is not found, the indexOf method returns -1.

Similarly, use the lastIndexOf method of the ArrayList class to find an element’s last index.

This method returns the index of the last occurrence of the specified object in the ArrayList. If the specified object is not found in the ArrayList, this method returns -1.

Example

Output

How to find element index in ArrayList of custom class objects?

Consider below given example which uses an ArrayList of custom class objects.

Output

Even if the object was in the ArrayList, the indexOf method could not find it and returned -1. That is because the indexOf and lastIndexOf methods rely on the equals method to compare the objects and since we have not implemented the equals method in the Customer class, it could not find it.

Here is the updated version of Customer class which implements equals and hashCode methods.

Output

This time the indexOf method worked and returned the right index for the object.

This example is a part of the Java ArrayList tutorial.

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

About the author

4 comments

    1. “That is because indexOf and lastIndexOf method relies on equals method to compare the objects”. You need to implement equals and hashcode method for it to work in your class. Make sure that these methods are implemented properly.

Leave a Reply

Your email address will not be published.