Collections

Find element in ArrayList using indexOf lastIndexOf methods example

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

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

Use indexOf method of ArrayList to find element index.

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

Similarly, use lastIndexOf method of ArrayList to find 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 ArrayList of custom class objects.

Output

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

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

Output

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

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

Join 1000+ fellow learners! Enter your email address below: