Vector setElementAt(K, int) in Java

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

Syntax:

void java.util.Vector.setElementAt(K obj, int index)

This method takes one argument. This method sets the component at the specified index of this vector to be the specified object.

Parameters: One parameter is required for this method.

obj: what the component is to be set to.index the specified index.

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 VectorsetElementAt {
    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;
        String obj = "Python";

        vector.setElementAt(obj, index);

        System.out.println(vector);
    }
}

Output:

[Hello, Python, C++, Program]


Approach 2: ArrayIndexOutOfBoundsException 

Java

import java.util.Vector;

public class VectorsetElementAt {
    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;
        String obj = "Python";

        vector.setElementAt(obj, index);

        System.out.println(vector);
    }
}

Output:

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


No comments:

Post a Comment