当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Vector indexOf()用法及代码示例


java.util.vector.indexOf(Object element)方法用于检查和查找向量中特定元素的出现。如果存在该元素,则返回该元素首次出现的索引,否则,如果向量不包含该元素,则返回-1。

用法:

Vector.indexOf(Object element)

参数:此方法接受Vector类型的必需参数element 。它指定需要在Vector中检查其出现的元素。


返回值:此方法返回向量中元素首次出现的索引或位置。否则,如果向量中不存在该元素,则返回-1。返回值是整数类型。

以下示例程序旨在说明Java.util.Vector.indexOf()方法:

示例1:

// Java code to illustrate indexOf() 
import java.util.*; 
  
public class VectorDemo { 
    public static void main(String args[]) 
    { 
  
        // Creating an empty Vector 
        Vector<String> vec_tor = new Vector<String>(); 
  
        // Use add() method to add elements in the Vector 
        vec_tor.add("Geeks"); 
        vec_tor.add("for"); 
        vec_tor.add("Geeks"); 
        vec_tor.add("10"); 
        vec_tor.add("20"); 
  
        // Displaying the Vector 
        System.out.println("Vector: " + vec_tor); 
  
        // The first position of an element 
        // is returned 
        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

示例2:

// Java code to illustrate indexOf() 
import java.util.*; 
  
public class VectorDemo { 
    public static void main(String args[]) 
    { 
  
        // Creating an empty Vector 
        Vector<Integer> vec_tor = new Vector<Integer>(); 
  
        // Use add() method to add elements in the Vector 
        vec_tor.add(1); 
        vec_tor.add(2); 
        vec_tor.add(3); 
        vec_tor.add(10); 
        vec_tor.add(20); 
  
        // Displaying the Vector 
        System.out.println("Vector: " + vec_tor); 
  
        // The first position of an element 
        // is returned 
        System.out.println("The first occurrence of Geeks is at index:"
                           + vec_tor.indexOf(2)); 
        System.out.println("The first occurrence of 10 is at index: "
                           + vec_tor.indexOf(20)); 
    } 
}
输出:
Vector: [1, 2, 3, 10, 20]
The first occurrence of Geeks is at index:1
The first occurrence of 10 is at index: 4


相关用法


注:本文由纯净天空筛选整理自kundankumarjha大神的英文原创作品 Vector indexOf() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。