Java Vector indexOf() 方法



描述

indexOf(Object elem) 方法用於搜尋給定引數的第一次出現。相等性使用 equals 方法進行測試。

宣告

以下是java.util.Vector.indexOf() 方法的宣告

public int indexOf(Object elem)

引數

elem − 輸入引數是一個物件

返回值

返回值是此向量中引數第一次出現的索引。如果找不到物件,則返回 -1。

異常

Java Vector indexOf(Object elem,int index) 方法

描述

這是前面 indexOf() 方法的另一個變體。唯一的區別是,對給定引數的第一次出現的搜尋從作為第二個引數提到的索引位置開始

宣告

以下是java.util.Vector.indexOf() 方法的宣告

public int indexOf(Object elem,int index)

引數

  • elem − 輸入引數是一個物件

  • index − 這是開始搜尋的非負索引

返回值

方法呼叫返回此向量中物件引數在位置 index 或之後在向量中第一次出現的索引。

異常

IndexOutOfBoundsException − 如果索引為負,則丟擲此異常

獲取整數向量元素索引示例

以下示例演示瞭如何使用 Java Vector indexOf(Object element) 方法獲取此向量中元素的索引。我們使用 add() 方法為每個元素向 Vector 物件新增幾個整數,並使用 indexOf(Object element) 方法獲取 3 的索引並將其打印出來。

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String[] args) {

      // create an empty Vector vec with an initial capacity of 4      
      Vector<Integer> vec = new Vector<>(4);

      // use add() method to add elements in the vector
      vec.add(4);
      vec.add(3);
      vec.add(2);
      vec.add(3);

      // let us get the index of 3
      System.out.println("Index of 3 is: "+vec.indexOf(3));
   }   
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果。請注意,3 第一次出現的索引是 1,所以列印 1 而不是 3。

Index of 3 is: 1

從其他索引開始獲取整數向量元素索引示例

以下示例演示瞭如何使用 Java Vector indexOf(Object element, Int index) 方法從給定索引開始獲取此向量中元素的索引。我們使用 add() 方法為每個元素向 Vector 物件新增幾個整數,並使用 indexOf() 方法獲取 3 的索引並將其打印出來。

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String[] args) {

      // create an empty Vector vec with an initial capacity of 4      
      Vector<Integer> vec = new Vector<>(4);

      // use add() method to add elements in the vector
      vec.add(4);
      vec.add(3);
      vec.add(2);
      vec.add(3);
      vec.add(2);
      vec.add(3);

      /** let us get the index of 3
      * starting search from 2nd index
      */
      System.out.println("Index of 3 :"+vec.indexOf(3,2));
   }   
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果。

Index of 3 :3

獲取字串向量元素索引示例

以下示例演示瞭如何使用 Java Vector indexOf(Object element) 方法獲取此向量中元素的索引。我們使用 add() 方法為每個元素向 Vector 物件新增幾個字串,並使用 indexOf(Object element) 方法獲取 C 的索引並將其打印出來。

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String[] args) {

      // create an empty Vector vec with an initial capacity of 4      
      Vector<String> vec = new Vector<>(4);

      // use add() method to add elements in the vector
      vec.add("D");
      vec.add("C");
      vec.add("A");
      vec.add("C");

      // let us get the index of C
      System.out.println("Index of C is: "+vec.indexOf("C"));
   }   
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果。請注意,C 第一次出現的索引是 1,所以列印 1 而不是 C。

Index of C is: 1
java_util_vector.htm
廣告