Vector remove(int) in Java

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

Syntax:

K java.util.Vector.remove(int index)

This method takes one argument. This method removes the element at the specified position in this Vector. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the Vector.

Parameters: One parameter is required for this method.

index: the index of the element to be removed.

Returns: element that was removed.

Throws:

ArrayIndexOutOfBoundsException - if the index is out of range(index < 0 || index >= size()).

Approach 1: When no exception

Java

import java.util.Vector;

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

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

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");
        int index = 1;

        System.out.println(vector.remove(index));
    }
}

Output:

Java


Approach 2: ArrayIndexOutOfBoundsException 

Java

import java.util.Vector;

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

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

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");
        int index = 5;

        System.out.println(vector.remove(index));
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 5 at java.base/java.util.Vector.remove(Vector.java:844)


No comments:

Post a Comment