# 使用索引在 Java 中搜索元素

> 原文： [https://beginnersbook.com/2014/06/search-elements-in-vector-using-index-java-example/](https://beginnersbook.com/2014/06/search-elements-in-vector-using-index-java-example/)

在本教程中，我们将学习以下四种使用索引值在`Vector`中搜索元素的方法。

1）`public int indexOf(Object o)`：返回`Vector`中第一次出现的对象`o`的索引。

2）`public int indexOf(Object o, int startIndex)`：返回此向量中第一次出现的对象`o`的索引，从`startIndex`（包括）开始向前搜索。

3）`public int lastIndexOf(Object o)`：返回`Vector`中最后一次出现的对象`o`的索引。

4）`public int lastIndexOf(Object o, int startIndex)`：它返回此向量中最后一次出现的指定元素的索引，从`startIndex`（包括）向后搜索。

#### 示例

在这个例子中，我们使用了上面提到的所有四种方法来证明它们的工作原理。

```java
import java.util.Vector;
public class SearchVector {
  public static void main(String[] args) { 
     // Create a Vector object
     Vector<String> vector = new Vector<String>();

     //Add elements to Vector
     vector.add("Kate");
     vector.add("Patt");
     vector.add("Kluge");
     vector.add("Karon");
     vector.add("Patt");
     vector.add("Monica");
     vector.add("Patt");

     //This would return the index of first occurrence
     int first_index = vector.indexOf("Patt");
     System.out.println("First Occurrence of Patt at index: "+first_index);

     //This would return the index of last occurrence
     int last_index = vector.lastIndexOf("Patt");
     System.out.println("Last Occurrence of Patt at index: "+last_index);

     //This would start search from index 2(inclusive)
     int after_index = vector.indexOf("Patt", 2);
     System.out.println("Occurrence after index 2: "+after_index);

     //This would search the element backward starting from index 6(inclusive)
     int before_index = vector.lastIndexOf("Patt", 6);
     System.out.println("Occurrence before index 6: "+before_index);
  } 
}
```

**输出：**

```java
First Occurrence of Patt at index: 1
Last Occurrence of Patt at index: 6
Occurrence after index 2: 4
Occurrence before index 6: 6

```

**参考**

[`Vector` javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/Vector.html "javadoc")