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

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 *