Java Vector indexOf()方法
java.util.vector.indexOf(Object element) 方法是用来检查和寻找一个特定元素在向量中的出现。如果该元素存在,则返回该元素第一次出现的索引,否则,如果向量不包含该元素,则返回-1。
语法
Vector.indexOf(Object element)
参数: 矢量类型的元素,这是必须的,因为它指定了需要在矢量中检查其出现的元素。
返回值: 该元素在向量中第一次出现的索引或位置。否则,如果该元素不存在于向量中,则返回 -1 。返回值是整数类型的。
例子1 :
// Java Program to illustrate indexOf() Method
// of Vector class
// Importing required classes
import java.util.*;
// Main class
// VectorDemo
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an empty Vector by creating object of
// Vector class of string type
Vector<String> vec_tor = new Vector<String>();
// Adding elements in the Vector
// using add() method
vec_tor.add("Geeks");
vec_tor.add("for");
vec_tor.add("Geeks");
vec_tor.add("10");
vec_tor.add("20");
// Print and display all elements in above vector
// object
System.out.println("Vector: " + vec_tor);
// Print commands where we are returning the 1st
// position of element in vector object using
// indexOf() method
System.out.println(
"The first occurrence of Geeks is at index:"
+ vec_tor.indexOf("Geeks"));
System.out.println(
"The first occurrence of 10 is at index: "
+ vec_tor.indexOf("10"));
}
}
输出
Vector: [Geeks, for, Geeks, 10, 20]
The first occurrence of Geeks is at index:0
The first occurrence of 10 is at index: 3
输出解析: 这里我们在向量中插入了一些元素,其中有几个元素是重复的。在上面的例子中,”Geeks “是Vector类中唯一被重复的元素,所以我们返回第一个出现的索引,所以我们返回’0’,而如果元素没有被重复,那么将简单地返回其索引。
例2 :
// Java Program to illustrate indexOf() Method
// of Vector class
// Importing required classes
import java.util.*;
// Main class
// VectorDemo
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an empty Vector
Vector<Integer> vec_tor = new Vector<Integer>();
// Adding elements in the Vector
// using add() method
vec_tor.add(1);
vec_tor.add(2);
vec_tor.add(3);
vec_tor.add(1);
vec_tor.add(5);
// Print and display all elements of vector object
System.out.println("Vector: " + vec_tor);
// Returning the 1st position of an element
// using indexOf() method
// Print and display commands
System.out.println("The first occurrence of 1 is at index : "+ vec_tor.indexOf(1));
System.out.println("The first occurrence of 3 is at index : "+ vec_tor.indexOf(7));
}
}
输出
Vector: [1, 2, 3, 1, 5]
The first occurrence of 1 is at index : 0
The first occurrence of 3 is at index : -1
输出解释: 正如我们上面所做的,在字符串的情况下,我们采取整数,这里唯一不同的是绕过一个不存在的元素,那么’-1’将被返回,因为在java中不存在任何负的索引,所以我们一般都会分配-1。
极客教程