- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Search an element of Vector in Java
An element of a Vector can be searched using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurrence of the element that is specified. If the element is not available in the Vector, then this method returns -1.
A program that demonstrates this is given as follows:
Example
import java.util.Vector; public class Demo { public static void main(String args[]) { Vector vec = new Vector(5); vec.add(4); vec.add(1); vec.add(7); vec.add(9); vec.add(2); vec.add(8); System.out.println("The Vector elements are: " + vec); System.out.println("The index of element 9 in Vector is: " + vec.indexOf(9)); System.out.println("The index of element 5 in Vector is: " + vec.indexOf(5)); } }
The output of the above program is as follows:
The Vector elements are: [4, 1, 7, 9, 2, 8] The index of element 9 in Vector is: 3 The index of element 5 in Vector is: -1
Now let us understand the above program.
The Vector is created. Then Vector.add() is used to add the elements to the Vector. Vector.indexOf() returns the index of the first occurrence of elements 9 and 5 and that is displayed. A code snippet which demonstrates this is as follows:
Vector vec = new Vector(5); vec.add(4); vec.add(1); vec.add(7); vec.add(9); vec.add(2); vec.add(8); System.out.println("The Vector elements are: " + vec); System.out.println("The index of element 9 in Vector is: " + vec.indexOf(9)); System.out.println("The index of element 5 in Vector is: " + vec.indexOf(5));
- Related Articles
- Search an element of ArrayList in Java
- Replace an element at a specified index of the Vector in Java
- Java Program to Recursively Linearly Search an Element in an Array
- How do you search for an element in an ArrayList in Java?
- Find the maximum element of a Vector in Java
- Find the minimum element of a Vector in Java
- Search Element in an Javascript Hash Table
- Swift Program to Search an Element in an Array
- Binary search in sorted vector of pairs in C++
- C++ Program to Search for an Element in a Binary Search Tree
- How to search an element in android ArrayBlockingQueue?
- Search a particular element in a LinkedList in Java
- How to minus every element of a vector with every element of another vector in R?
- How to search for an element in JavaScript array?
- Golang program to search an element in the slice

Advertisements