Vector
Search elements in Vector from index example
This is an example of how to search an element in a Vector from its index. Searching elements in a Vector from index implies that you should:
- Create a new Vector.
- Populate the vector with elements, with
add(E e)
API method of Vector. - Invoke
indexOf(Object o, int index)
API method of Vector. The method returns the index of the first occurrence of the specified element in this vector, searching forwards from index, if the element is found in the Vector. If the element does not exist in the Vector it returns -1.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.Vector; public class SearchVectorElementFromIndex { 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"); vector.add("element_2"); vector.add("element_3"); vector.add("element_2"); /* int indexOf(Object element, int startIndex) method returns the index of the first occurence of the specified element after startIndex (inclusive) in Vector or -1 if not found. To get last index of the specified element before the specified index (inclusive) in Vector use the int lastIndexOf(Object element, int startIndex) operation instead. */ int index = vector.indexOf("element_2", 3); System.out.println("Found element_2 after position 3 : " + (index == -1?false:true) + ", in position : " + index); int lastIndex = vector.lastIndexOf("element_2", 6); System.out.println("Found element_2 before position 5 : " + (lastIndex == -1?false:true) + ", in position : " + lastIndex); } }
Output:
Found element_2 after position 3 : true, in position : 4
Found element_2 before position 5 : true, in position : 6
This was an example of how to search an element in a Vector from its index in Java.