Java Examples - Get the Index Value of Vector Elements

Java 实例Java Examples

The following example demonstrates using the sort() method of the Collections class to sort a vector and using the binarySearch() method to get the index value of vector elements:

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("The index value of the element is:" + index); } }

The output of running the above code is:

[A, D, M, O, X]
元素索引值为 : 1

Java 实例Java Examples

Other Extensions