原文: 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(包括)向后搜索。
示例
在这个例子中,我们使用了上面提到的所有四种方法来证明它们的工作原理。
import java.util.Vector;public class SearchVector {public static void main(String[] args) {// Create a Vector objectVector<String> vector = new Vector<String>();//Add elements to Vectorvector.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 occurrenceint first_index = vector.indexOf("Patt");System.out.println("First Occurrence of Patt at index: "+first_index);//This would return the index of last occurrenceint 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
参考
