原文: 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(包括)向后搜索。

示例

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

  1. import java.util.Vector;
  2. public class SearchVector {
  3. public static void main(String[] args) {
  4. // Create a Vector object
  5. Vector<String> vector = new Vector<String>();
  6. //Add elements to Vector
  7. vector.add("Kate");
  8. vector.add("Patt");
  9. vector.add("Kluge");
  10. vector.add("Karon");
  11. vector.add("Patt");
  12. vector.add("Monica");
  13. vector.add("Patt");
  14. //This would return the index of first occurrence
  15. int first_index = vector.indexOf("Patt");
  16. System.out.println("First Occurrence of Patt at index: "+first_index);
  17. //This would return the index of last occurrence
  18. int last_index = vector.lastIndexOf("Patt");
  19. System.out.println("Last Occurrence of Patt at index: "+last_index);
  20. //This would start search from index 2(inclusive)
  21. int after_index = vector.indexOf("Patt", 2);
  22. System.out.println("Occurrence after index 2: "+after_index);
  23. //This would search the element backward starting from index 6(inclusive)
  24. int before_index = vector.lastIndexOf("Patt", 6);
  25. System.out.println("Occurrence before index 6: "+before_index);
  26. }
  27. }

输出:

  1. First Occurrence of Patt at index: 1
  2. Last Occurrence of Patt at index: 6
  3. Occurrence after index 2: 4
  4. Occurrence before index 6: 6

参考

Vector javadoc