Java Vector lastIndexOf()方法

Java Vector lastIndexOf()方法

Java.util.Vector .lastIndexOf(Object element)方法用于检查和查找某个特定元素在向量中的出现。如果该元素存在于矢量中,那么lastIndexOf()方法将返回该元素最后出现的索引,否则它将返回-1。该方法用于查找某个特定元素在向量中的最后出现情况。

语法

Vector.lastIndexOf(Object element)

参数: 参数元素的类型是矢量。它指的是最后出现的元素需要被检查。

返回值: 该方法返回元素在Vector中最后出现的位置。如果元素在Vector中不存在,那么该方法返回-1。返回的值是整数类型的。

以下程序说明了Java.util.Vector.lastIndexOf()方法。

程序1 :

// Java code to illustrate lastIndexOf()
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 last position of an element is returned
        System.out.println("Last occurrence of Geeks is at index: "
                           + vec_tor.lastIndexOf("Geeks"));
        System.out.println("Last occurrence of 10 is at index: "
                           + vec_tor.lastIndexOf("10"));
    }
}

输出:

Vector: [Geeks, for, Geeks, 10, 20]
Last occurrence of Geeks is at index: 2
Last occurrence of 10 is at index: 3

程序2

// Java code to illustrate lastIndexOf()
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(10);
        vec_tor.add(22);
        vec_tor.add(3);
        vec_tor.add(10);
        vec_tor.add(20);
  
        // Displaying the Vector
        System.out.println("Vector: " + vec_tor);
  
        // The last position of an element is returned
        System.out.println("Last occurrence of 10 is at index: "
                           + vec_tor.lastIndexOf(10));
        System.out.println("Last occurrence of 20 is at index: "
                           + vec_tor.lastIndexOf(20));
    }
}

输出:

Vector: [10, 22, 3, 10, 20]
Last occurrence of 10 is at index: 3
Last occurrence of 20 is at index: 4

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程