可以使用java.util.ArrayList.indexOf()方法搜索Vector的元素。此方法返回指定元素首次出现的索引。如果Vector中的元素不可用,则此方法返回-1。
演示此过程的程序如下:
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 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
现在让我们了解上面的程序。
向量已创建。然后使用Vector.add()将元素添加到Vector。Vector.indexOf()返回元素9和5首次出现的索引并显示。演示此代码段如下:
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));