Vector lastIndexOf(Object, int) in Java

lastIndexOf(Object, int): This method is available in java.util.Vector class of Java.

Syntax:

int java.util.Vector.lastIndexOf(Object o, int index)

This method takes two arguments. This method returns the index of the last occurrence of the specified element in this vector, searching backward from the index, or returns -1 if the element is not found.

Parameters: Two parameters are required for this method.

o: the element to search for.

index: index to start searching backward from.

Returns: the index of the last occurrence of the element at a position less than or equal to the index in this vector;-1 if the element is not found.

Throws:

IndexOutOfBoundsException - if the specified index is greater than or equal to the current size of this vector

Approach 1: When no exception

Java

import java.util.Vector;

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

        Vector<String> vector = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        Object o = "C++";
        int index = 1;

        System.out.println(vector.lastIndexOf(o, index));
    }
}

Output:

-1


Approach 2: IndexOutOfBoundsException 

Java

import java.util.Vector;

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

        Vector<String> vector = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        Object o = "C++";
        int index = 5;

        System.out.println(vector.lastIndexOf(o, index));
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: 5 >= 4 at java.base/java.util.Vector.lastIndexOf(Vector.java:439)


No comments:

Post a Comment