Java Vector contains(Object o) Example

In this example we will learn how to search if a element is present in the Vector or not. We will use the contains(Object o) method of java.util.Vector class.

Signature

public boolean contains(Object o)

This method returns true if the vector contains the specified element.

Example

The following example shows the usage of java.util.Vector.contains(o) method.

import java.util.Vector;

public class ContainsMethodVectorExample 
{
    public static void main(String args[])
    {
        // create an empty Vector
        Vector vector1 = new Vector();
        
        // use add() method to add elements to the Vector
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");
        
        //Checking if Element2 is present or not        
        if(vector1.contains("Element2"))
        {
            System.out.println("Element2 is present at the index "+vector1.indexOf("Element2"));
        }
        else
        {
            System.out.println("Element2 is not present in the list");
        }
    }
}

Output

Element2 is present at the index 1

Leave a Reply

Your email address will not be published. Required fields are marked *