Easy Tutorial
❮ Java Hashmap Computeifpresent Java Object Notifyall ❯

Java Example - Getting the Index of a Vector Element

Java Example

The following example demonstrates how to sort a vector using the sort() method of the Collections class and then use the binarySearch() method to get the index of a vector element:

Main.java File

import java.util.Collections;
import java.util.Vector;

public class Main {
   public static void main(String[] args) {
      Vector v = new Vector();
      v.add("X");
      v.add("M");
      v.add("D");
      v.add("A");
      v.add("O");
      Collections.sort(v);
      System.out.println(v);
      int index = Collections.binarySearch(v, "D");
      System.out.println("Element index is : " + index);
   }
}

The output of the above code is:

[A, D, M, O, X]
Element index is : 1

Java Example

❮ Java Hashmap Computeifpresent Java Object Notifyall ❯