Java 集合 使用索引搜索元素

来源:这里教程网 时间:2026-02-17 20:13:25 作者:

在本教程中,我们将学习以下四种使用索引值在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(包括)向后搜索。

示例

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

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);  } }

输出:

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

相关推荐