Searching for an element in Vector with indexOf in Java

Vector has 4 ways to search for elements using the indexOf():

1) public int indexOf(Object obj): returns the index of the first occurrence of the object obj found in Vector.

2) public int indexOf(Object obj, int indiceDebut): returns the index of the first occurrence of the obj object found in Vector, starting the search from a leading index.

3) public int lastIndexOf(Object obj): returns the index of the last found occurrence of the obj object in Vector.

4) public int lastIndexOf(Object obj, int indiceDebut): returns the index of the first occurrence found of the obj object in Vector, looking backwards from a index start.

Example:

This example shows the use of the 4 methods mentioned and how they work:

import java.util.Collections; 
import java.util.Vector;
public class indexOf {
public static void main(String[] args) {

//create vector
Vector vector = new Vector();

//add elements to vector
vector.add("blue");
vector.add("orange");
vector.add("green");
vector.add("black");
vector.add("gray");
vector.add("green");
vector.add("yellow");
vector.add("green");

System.out.println(vector);

//returns the first occurrence
int firstOcc = vector.indexOf("green");
System.out.println("First occurrence of green"+
" in position: "+firstOcc);

//starts the search from the 3
int index after Index = vector.indexOf("green", 3);
System.out.println("First occurrence of green"+
" after index 2: "+afterIndex);

//returns the last occurrence
int lastOcc = vector.lastIndexOf("green");
System.out.println("Last occurrence of green"+
" in the position: "+lastOcc);

//starts the search backwards from the index 5
int beforeIndex = vector.lastIndexOf("green", 6);
System.out.println("First occurrence of green"+
" before index 6: "+beforeIndex);
}
}
Output:

[blue, orange, green, black, gray, green, yellow, green]
First occurrence of green in position: 2
First occurrence of green after index 2: 5
Last green occurrence in position: 7
First green occurrence before index 6: 5