當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。