Vector set(int, K) in Java

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

Syntax:

K java.util.Vector.set(int index, K element)

This method takes one argument. This method replaces the element at the specified position in this Vector with the specified element.

Parameters: One parameter is required for this method.

index: index of the element to replace.element element to be stored at the specified position.

Returns: the element previously at the specified position.

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 Vectorset {
    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 element = "Python";

        System.out.println(vector.set(index, element));
    }
}

Output:

Java


Approach 2: ArrayIndexOutOfBoundsException

Java

import java.util.Vector;

public class Vectorset {
    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 element = "Python";

        System.out.println(vector.set(index, element));
    }
}

Output:

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


No comments:

Post a Comment