Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to use the Vector.lastIndexOf method in Java

Programming Bytes

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index, and the size of a Vector can be increased or decreased. Read more about Vector here.

We can use the lastIndexOf method to get the last occurrence of the specified value from a Vector object.

Syntax

public int lastIndexOf(Object obj);

Parameters

  • obj: The element to be searched for in the Vector.

Return value

This method returns the last index at which the specified element is present in the Vector.

If the element is not present in the Vector, then the lastIndexOf method returns -1.

Code

The code below demonstrates how to use the lastIndexOf method.

import java.util.Vector;
class LastIndexOfExample {
    public static void main( String args[] ) {
      Vector<String> vector = new Vector<>();
      vector.add("1");
      vector.add("2");
      vector.add("1");
      System.out.println("The vector is " + vector);

      System.out.println("Last Index of element '1' is : " + vector.lastIndexOf("1"));
      System.out.println("Last Index of element '2' is : " + vector.lastIndexOf("2"));
      System.out.println("Last Index of element '3' is : " + vector.lastIndexOf("3"));
    }
}

Explanation

In the code above:

  • In line 1, we import the Vector class.

  • In line 4, we create a new object for Vector object with the name vector.

  • From lines 5 to 7, we use the add method of the vector object to add three elements ("1","2","3") to the vector.

  • In line 10, we use the lastIndexOf method of the vector object to get the index of the last occurrence of the element "1". The element "1" is present at two indices:,0 and 2. We get 0 as a result since that is the last occurrence.

  • In line 11, we use the lastIndexOf method of the vector object to get the index of the last occurrence of the element "2". The element "2" is only present at index 1, so it is returned.

  • In line 12, we use the lastIndexOf method of the vector object to get the index of the last occurrence of the element "3". The element "3" is not present in the vector, so -1 is returned.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring