Search elements in Vector example

In this example we shall show you how to search elements in a Vector. The Vector API provides us with methods for such operations. To search elements in a Vector one should perform the following steps:

  • Create a new Vector.
  • Populate the vector with elements, with add(E e) API method of Vector.
  • Invoke contains(Object o) API method of Vector to check if an element exists in the Vector. The method returns true if this vector contains the specified element.
  • Invoke indexOf(Object o) API method of Vector. The method returns the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element.
  • To get the index of the last occurance of the specified element in Vector use the lastIndexOf(Object element) method instead,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;
import java.util.Vector;
public class SearchElementsVector {
  public static void main(String[] args) {
    // Create a Vector and populate it with elements
    Vector vector = new Vector();

boolean contains(Object element) operation returns true 

if the Vector contains the specified object, false otherwise.
    boolean found = vector.contains("element_2");
    System.out.println("Found element_2 : " + found);

int indexOf(Object element) operation returns the index of the 

first occurance of the specified element in Vector or -1 if 

the specific element is not found. To get the index of the last 

occurance of the specified element in Vector use the

int lastIndexOf(Object element) operation instead.
    int index = vector.indexOf("element_3");
    System.out.println("Found element_3 : " + (index == -1?false:true) + ", in position : " + index);
    int lastIndex = vector.lastIndexOf("element_1");
    System.out.println("Found element_1 : " + (lastIndex == -1?false:true) + ", in position : " + lastIndex);


Found element_2 : true
Found element_3 : true, in position : 2
Found element_1 : true, in position : 3

This was an example of how to search elements in a Vector in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button