Skip to content

Find Vector Element using indexOf and lastIndexOf methods in Java Example

This example shows how to find an element in a Vector using the indexOf and lastIndexOf methods. This example also shows how to find the element index in the Vector of custom class objects.

How to find the element index in Vector in Java?

How to find the index of the first occurrence of an element using the indexOf method?

The Vector indexOf method returns the index of the first occurrence of the specified element within the vector object.

It returns -1 if the specified element is not found in the vector object.

Output

The overloaded indexOf method returns the index of the first occurrence of the given element starting from the specified index of the vector object.

Output

How to find the index of the last occurrence of an element using the lastIndexOf method?

The Vector lastIndexOf method returns the index of the last occurrence of the specified element in the vector object.

It returns -1 if the element is not found in the vector object.

Output

The overloaded lastIndexOf method returns the last index of the specified element starting from the given index searching backward.

Output

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

If the Vector elements are objects of a custom class, then the class must implement the equals (and preferably hashCode) method. If the custom class has not overridden these methods, the indexOf and lastIndexOf methods will not be able to find the element in the Vector.

Output

This example is a part of the Vector in Java Tutorial with Examples.

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

References:
Java 8 Vector Documentation

About the author

Leave a Reply

Your email address will not be published.