Vector

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();
    vector.add("element_1");
    vector.add("element_2");
    vector.add("element_3");
    vector.add("element_1");
 
    /*

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);
 
  }
}

Output:

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.

Ilias Tsagklis

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

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

0 Comments
Inline Feedbacks
View all comments
Back to top button