Vector removeElementAt(int) in Java

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

Syntax:

void java.util.Vector.removeElementAt(int index)

This method takes one argument. This method deletes the component at the specified index.

Note: Each component in this vector with an index greater or equal to the specified index is shifted downward to have an index one smaller than the value it had previously. The size of this vector is decreased by 1.

Parameters: One parameter is required for this method.

index: the index of the object to remove.

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 VectorremoveElementAt {
    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;
        vector.removeElementAt(index);

        System.out.println(vector);
    }
}

Output:

[Hello, C++, Program]


Approach 2: ArrayIndexOutOfBoundsException

Java

import java.util.Vector;

public class VectorremoveElementAt {
    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;
        vector.removeElementAt(index);

        System.out.println(vector);
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 >= 4 at java.base/java.util.Vector.removeElementAt(Vector.java:549)


No comments:

Post a Comment