Java Utility Library

Java Vector - set() Method



The java.util.Vector.set() method is used to replaces the element at the specified index in the vector with the specified element.

Syntax

public E set(int index, E element)

Here, E is the type of element maintained by the container.


Parameters

index Specify index number of the element to replace.
element Specify element to replace with.

Return Value

Returns the element at specified index of the vector.

Exception

Throws IndexOutOfBoundsException, if the index is out of range i.e., (index < 0 || index > size()).

Example:

In the example below, the java.util.Vector.set() method is used to replace the element at the specified index in the vector with the specified element.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<Integer> MyVector = new Vector<Integer>();

    //populating vector
    MyVector.add(10);
    MyVector.add(20);
    MyVector.add(30);
    MyVector.add(40);
    MyVector.add(50);

    System.out.println("Before method call, MyVector contains: " + MyVector);
    MyVector.set(1, 1000);
    System.out.println("After method call, MyVector contains: " + MyVector);    
  }
}

The output of the above code will be:

Before method call, MyVector contains: [10, 20, 30, 40, 50]
After method call, MyVector contains: [10, 1000, 30, 40, 50]

❮ Java.util - Vector